<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description"
        content="GitCodeTree - Professional GitCode directory tree generator and card sharing tool with multiple styles and export formats">
    <meta name="keywords" content="GitCode, directory tree, project structure, share card, development tools">
    <title>GitCodeTree - GitCode Directory Tree Generator & Card Sharing</title>

    <!-- 預加載關鍵資源 -->
    <link rel="preload" href="https://cdn.tailwindcss.com" as="script">
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" as="style">

    <!-- 外部依賴 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" defer></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* CSS 變量定義 */
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-gradient: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            --accent-gradient: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            --success-gradient: linear-gradient(135deg, #2ed573 0%, #1e90ff 100%);
            --dark-gradient: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
            --glass-bg: rgba(255, 255, 255, 0.95);
            --glass-border: rgba(255, 255, 255, 0.3);
            --text-primary: #1a202c;
            --text-secondary: #4a5568;
            --text-muted: #718096;
            --border-color: rgba(0, 0, 0, 0.08);
            --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.04);
            --shadow-md: 0 4px 20px rgba(0, 0, 0, 0.08);
            --shadow-lg: 0 10px 40px rgba(0, 0, 0, 0.12);
            --shadow-xl: 0 20px 60px rgba(0, 0, 0, 0.15);
            --radius-sm: 6px;
            --radius-md: 10px;
            --radius-lg: 14px;
            --radius-xl: 20px;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            --transition-fast: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
            --spacing-xs: 0.25rem;
            --spacing-sm: 0.5rem;
            --spacing-md: 1rem;
            --spacing-lg: 1.5rem;
            --spacing-xl: 2rem;
            --spacing-2xl: 3rem;
        }

        /* 暗黑模式變量 */
        .dark-mode {
            --glass-bg: rgba(26, 32, 44, 0.95);
            --glass-border: rgba(255, 255, 255, 0.1);
            --text-primary: #f7fafc;
            --text-secondary: #cbd5e0;
            --text-muted: #a0aec0;
            --border-color: rgba(255, 255, 255, 0.1);
            --secondary-gradient: linear-gradient(135deg, #2d3748 0%, #1a202c 100%);
        }

        /* 基礎樣式 */
        .directory-tree {
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            line-height: 1.6;
        }

        /* 卡片樣式組件 */
        .mac-card {
            background: linear-gradient(145deg, #2d3748, #1a202c);
            border-radius: var(--radius-xl);
            overflow: hidden;
            box-shadow: var(--shadow-xl);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            position: relative;
        }

        .mac-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
        }

        .mac-header {
            background: linear-gradient(145deg, #4a5568, #2d3748);
            padding: 12px 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .mac-button {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .mac-content {
            padding: 24px;
            display: flex;
            gap: 20px;
            align-items: flex-start;
        }

        .mac-info {
            flex: 1;
            color: #e2e8f0;
        }

        .mac-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #f7fafc;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }

        .mac-desc {
            font-size: 0.875rem;
            color: #cbd5e0;
            margin-bottom: 16px;
        }

        .mac-stats {
            display: flex;
            gap: 16px;
            font-size: 0.875rem;
        }
    
        .gitee-card {
            background: var(--glass-bg);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-xl);
            overflow: hidden;
            box-shadow: var(--shadow-lg);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            position: relative;
        }

        .gitee-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
        }

        .gitee-header {
            background: #f6f8fa;
            padding: 16px;
            border-bottom: 1px solid #d0d7de;
            display: flex;
            align-items: center;
            gap: 8px;
        }
       
        .gitee-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #0969da;
            display: flex;
            align-items: center;
        }

        .gitee-badge {
            background: #ddf4ff;
            color: #0969da;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
            margin-left: auto;
        }

        .gitee-content {
            padding: 16px;
            display: flex;
            gap: 20px;
        }

        .gitee-info {
            flex: 1;
        }

        .gitee-desc {
            color: #656d76;
            margin-bottom: 16px;
        }

        .gitee-stats {
            display: flex;
            gap: 16px;
            font-size: 0.875rem;
            color: #656d76;
        }
    
        .material-card {
            background: var(--glass-bg);
            border-radius: var(--radius-xl);
            box-shadow: var(--shadow-lg);
            overflow: hidden;
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid var(--border-color);
            position: relative;
        }

        .material-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
        }

        .material-content {
            padding: 24px;
        }

        .material-top {
            display: flex;
            gap: 20px;
            align-items: flex-start;
            margin-bottom: 20px;
        }

        .material-info {
            flex: 1;
        }

        .material-title {
            font-size: 1.5rem;
            font-weight: 400;
            color: #202124;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }

        .material-desc {
            color: #5f6368;
            line-height: 1.5;
        }

        .material-divider {
            height: 1px;
            background: #e8eaed;
            margin: 20px 0;
        }

        .material-stats {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #5f6368;
        }

        .material-stats-left {
            display: flex;
            gap: 20px;
        }
    
        .modern-card {
            background: var(--primary-gradient);
            border-radius: var(--radius-xl);
            color: white;
            overflow: hidden;
            box-shadow: var(--shadow-xl);
            position: relative;
        }

        .modern-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
        }

        .modern-content {
            padding: 28px;
        }

        .modern-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }

        .modern-desc {
            opacity: 0.9;
            margin-bottom: 24px;
            line-height: 1.5;
        }

        .modern-footer {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
        }

        .modern-stats {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .modern-stat {
            opacity: 0.9;
            font-size: 0.9rem;
        }
    
        .qr-container {
            background: white;
            padding: 8px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .mac-tree-container {
            background: linear-gradient(145deg, #2d3748, #1a202c);
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.3);
            width: 900px;
            color: #e2e8f0;
        }

        .mac-tree-header {
            background: linear-gradient(145deg, #4a5568, #2d3748);
            padding: 12px 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .mac-tree-content {
            padding: 20px;
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            line-height: 1.6;
            white-space: pre;
            overflow: visible;
            font-size: 14px;
        }
    
        /* 暗黑模式 */
        .dark-mode {
            background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
            color: #e2e8f0;
        }
        
        .dark-mode .glass-card {
            background: rgba(45, 55, 72, 0.8);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .dark-mode .input-field {
            background: rgba(45, 55, 72, 0.9);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: #e2e8f0;
        }
        
        .dark-mode .input-field:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }
        
        .dark-mode .btn-secondary {
            background: rgba(45, 55, 72, 0.9);
            color: #e2e8f0;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .dark-mode .btn-secondary:hover {
            background: rgba(45, 55, 72, 1);
        }
        
        .dark-mode .advanced-options {
            background-color: rgba(45, 55, 72, 0.8);
        }
        
        .dark-mode .advanced-options-title {
            color: #cbd5e0;
        }
        
        .dark-mode .option-label {
            color: #cbd5e0;
        }
        
        .dark-mode .section-title {
            color: #e2e8f0;
        }
        
        .dark-mode .result-container {
            background: rgba(45, 55, 72, 0.9);
        }
        
        .dark-mode .directory-tree-container {
            background: rgba(26, 32, 44, 0.8);
            color: #e2e8f0;
        }
        
        .dark-mode .logo-text {
            background: linear-gradient(135deg, #90cdf4 0%, #a78bfa 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .dark-mode .footer {
            color: #a0aec0;
        }
        
        .dark-mode .bg-blue-50 {
            background-color: rgba(66, 153, 225, 0.1);
        }
        
        .dark-mode .border-blue-200 {
            border-color: rgba(66, 153, 225, 0.2);
        }
        
        .dark-mode .text-blue-700 {
            color: #90cdf4;
        }
        
        .dark-mode .text-blue-800 {
            color: #63b3ed;
        }
        
        .dark-mode .bg-red-50 {
            background-color: rgba(245, 101, 101, 0.1);
        }
        
        .dark-mode .border-red-200 {
            border-color: rgba(245, 101, 101, 0.2);
        }
        
        .dark-mode .text-red-600 {
            color: #fc8181;
        }
        
        .dark-mode .text-red-800 {
            color: #f56565;
        }
        
        .dropdown {
            position: relative;
            display: inline-block;
        }

        .dropdown-content {
            display: none;
            position: absolute;
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            min-width: 160px;
            box-shadow: var(--shadow-lg);
            z-index: 1000;
            border-radius: var(--radius-md);
            overflow: hidden;
            border: 1px solid var(--border-color);
            right: 0;
            top: 100%;
            margin-top: var(--spacing-sm);
            opacity: 0;
            transform: translateY(-10px);
            transition: all 0.2s ease-out;
        }

        .dropdown-content.show {
            opacity: 1;
            transform: translateY(0);
        }

        .language-dropdown {
            max-height: 300px;
            overflow-y: auto;
        }

        .dropdown-content a {
            color: var(--text-primary);
            padding: var(--spacing-sm) var(--spacing-md);
            text-decoration: none;
            display: flex;
            align-items: center;
            transition: var(--transition-fast);
            font-size: 0.9rem;
        }

        .dropdown-content a:hover {
            background: rgba(102, 126, 234, 0.1);
            color: #667eea;
        }

        /* 下拉菜單顯示由JavaScript控制 */
        
        .advanced-options {
            background: var(--glass-bg);
            border-radius: var(--radius-lg);
            padding: var(--spacing-lg);
            margin-top: var(--spacing-lg);
            border: 1px solid var(--border-color);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }

        .advanced-options-title {
            font-weight: 600;
            margin-bottom: var(--spacing-md);
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            font-size: 1.1rem;
        }

        .advanced-options-content {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: var(--spacing-lg);
        }

        .option-group {
            display: flex;
            flex-direction: column;
        }

        .option-label {
            font-size: 0.9rem;
            font-weight: 500;
            color: var(--text-secondary);
            margin-bottom: var(--spacing-sm);
        }

        /* 全局樣式 */
        * {
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            background: var(--secondary-gradient);
            min-height: 100vh;
            transition: var(--transition);
            margin: 0;
            padding: 0;
            color: var(--text-primary);
            line-height: 1.6;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        /* 添加背景裝飾 */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: 
                radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 20%, rgba(255, 107, 107, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 40% 40%, rgba(46, 213, 115, 0.1) 0%, transparent 50%);
            pointer-events: none;
            z-index: -1;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: var(--spacing-2xl) var(--spacing-md);
            position: relative;
        }
        
        .glass-card {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: var(--radius-xl);
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--glass-border);
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }

        .glass-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
        }
        
        .glass-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-xl);
        }
        
        .btn-primary {
            background: var(--primary-gradient);
            color: white;
            border: none;
            border-radius: var(--radius-md);
            padding: var(--spacing-md) var(--spacing-xl);
            font-weight: 600;
            font-size: 0.95rem;
            transition: var(--transition);
            box-shadow: var(--shadow-md);
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: var(--spacing-sm);
            position: relative;
            overflow: hidden;
        }

        .btn-primary::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }

        .btn-primary:hover::before {
            left: 100%;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .btn-primary:active {
            transform: translateY(0);
        }
        
        .btn-secondary {
            background: var(--glass-bg);
            color: var(--text-secondary);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-md);
            padding: var(--spacing-sm) var(--spacing-lg);
            font-weight: 500;
            font-size: 0.9rem;
            transition: var(--transition-fast);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        
        .btn-secondary:hover {
            background: rgba(255, 255, 255, 0.95);
            transform: translateY(-1px);
            box-shadow: var(--shadow-sm);
            border-color: rgba(102, 126, 234, 0.2);
        }
        
        .input-field {
            background: var(--glass-bg);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-md);
            padding: var(--spacing-md) var(--spacing-lg);
            font-size: 1rem;
            transition: var(--transition-fast);
            width: 100%;
            color: var(--text-primary);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        
        .input-field:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            transform: translateY(-1px);
        }

        .input-field::placeholder {
            color: var(--text-muted);
            font-weight: 400;
        }
        
        .section-title {
            font-size: 1.75rem;
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: var(--spacing-xl);
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
            position: relative;
        }

        .section-title::after {
            content: '';
            flex: 1;
            height: 2px;
            background: linear-gradient(90deg, var(--primary-gradient), transparent);
            margin-left: var(--spacing-md);
        }
        
        .result-container {
            background: var(--glass-bg);
            border-radius: var(--radius-md);
            padding: 1.5rem;
            margin-top: 1.5rem;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--glass-border);
        }
        
        .directory-tree-container {
            background: var(--glass-bg);
            border-radius: var(--radius-sm);
            padding: 1rem;
            max-height: 400px;
            overflow-y: auto;
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            line-height: 1.6;
            border: 1px solid var(--border-color);
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--spacing-2xl);
            padding: var(--spacing-lg) 0;
        }
        
        .logo {
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
        }
        
        .logo-text {
            font-size: 2rem;
            font-weight: 800;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            letter-spacing: -0.02em;
        }
        
        .theme-toggle {
            background: var(--glass-bg);
            border: 1px solid var(--border-color);
            border-radius: 50%;
            width: 44px;
            height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: var(--transition);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            box-shadow: var(--shadow-sm);
        }
        
        .theme-toggle:hover {
            background: rgba(255, 255, 255, 0.95);
            transform: scale(1.05);
            box-shadow: var(--shadow-md);
        }

        .theme-toggle:active {
            transform: scale(0.95);
        }
        
        .footer {
            text-align: center;
            margin-top: var(--spacing-2xl);
            color: var(--text-secondary);
            font-size: 0.9rem;
            display: flex;
            flex-direction: column;
            gap: var(--spacing-lg);
            padding: var(--spacing-xl) 0;
            border-top: 1px solid var(--border-color);
        }
        
        .footer-links {
            display: flex;
            justify-content: center;
            gap: var(--spacing-xl);
            flex-wrap: wrap;
        }
        
        .footer-link {
            color: var(--text-secondary);
            text-decoration: none;
            transition: var(--transition-fast);
            cursor: pointer;
            background: none;
            border: none;
            font-size: inherit;
            padding: var(--spacing-sm) var(--spacing-md);
            border-radius: var(--radius-sm);
        }
        
        .footer-link:hover {
            color: #667eea;
            background: rgba(102, 126, 234, 0.1);
            transform: translateY(-1px);
        }

        /* 工具類 */
        .sr-only {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0, 0, 0, 0);
            white-space: nowrap;
            border: 0;
        }

        .focus-visible {
            outline: 2px solid #667eea;
            outline-offset: 2px;
        }

        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
        
        .loader-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }
        
        .loader {
            width: 40px;
            height: 40px;
            position: relative;
        }
        
        .loader-circle {
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            border: 3px solid transparent;
            border-top-color: #667eea;
            animation: spin 1.5s cubic-bezier(0.68, -0.55, 0.265, 1.55) infinite;
        }
        
        .loader-circle:nth-child(2) {
            width: 80%;
            height: 80%;
            top: 10%;
            left: 10%;
            border-top-color: #764ba2;
            animation-delay: 0.2s;
        }
        
        .loader-circle:nth-child(3) {
            width: 60%;
            height: 60%;
            top: 20%;
            left: 20%;
            border-top-color: #9f7aea;
            animation-delay: 0.4s;
        }
        
        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
        
        .loader-text {
            margin-top: 1rem;
            color: #6b7280;
            font-size: 0.875rem;
        }
        
        .loader-dots {
            display: inline-flex;
            gap: 4px;
        }
        
        .loader-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #667eea;
            animation: bounce 1.4s infinite ease-in-out both;
        }
        
        .loader-dot:nth-child(1) {
            animation-delay: -0.32s;
        }

        .loader-dot:nth-child(2) {
            animation-delay: -0.16s;
        }
        
        @keyframes bounce {

            0%,
            80%,
            100% {
                transform: scale(0);
            }

            40% {
                transform: scale(1);
            }
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 16px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.3);
        }
        
        .dark-mode .modal-content {
            background-color: #2d3748;
            color: #e2e8f0;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }
        
        .modal-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1a202c;
        }
        
        .dark-mode .modal-title {
            color: #e2e8f0;
        }
        
        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: color 0.3s ease;
        }
        
        .close:hover {
            color: #667eea;
        }
        
        .modal-body {
            line-height: 1.6;
        }
        
        .modal-body h3 {
            margin-top: 1.5rem;
            margin-bottom: 0.75rem;
            font-size: 1.25rem;
            font-weight: 600;
            color: #1a202c;
        }
        
        .dark-mode .modal-body h3 {
            color: #e2e8f0;
        }
        
        .modal-body p {
            margin-bottom: 1rem;
        }
        
        .modal-body ul {
            margin-left: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .modal-body li {
            margin-bottom: 0.5rem;
        }
        
        .modal-body code {
            background-color: #f1f5f9;
            padding: 0.125rem 0.25rem;
            border-radius: 4px;
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            font-size: 0.875rem;
        }
        
        .dark-mode .modal-body code {
            background-color: #4a5568;
        }
        
        /* 響應式設計 */
        @media (max-width: 768px) {
            .container {
                padding: var(--spacing-md);
            }
            
            .header {
                flex-direction: column;
                gap: var(--spacing-lg);
                align-items: flex-start;
                margin-bottom: var(--spacing-xl);
            }

            .logo-text {
                font-size: 1.75rem;
            }

            .section-title {
                font-size: 1.5rem;
            }

            .section-title::after {
                display: none;
            }
            
            .advanced-options-content {
                grid-template-columns: 1fr;
                gap: var(--spacing-md);
            }
            
            .modal-content {
                margin: 5% auto;
                padding: var(--spacing-lg);
                width: 95%;
                max-height: 90vh;
            }
            
            .footer-links {
                flex-direction: column;
                gap: var(--spacing-md);
            }

            .btn-primary,
            .btn-secondary {
                width: 100%;
                justify-content: center;
                padding: var(--spacing-md) var(--spacing-lg);
            }

            .flex-col.sm\:flex-row {
                flex-direction: column;
            }

            .space-y-4.sm\:space-y-0.sm\:space-x-4>*+* {
                margin-top: var(--spacing-md);
                margin-left: 0;
            }

            .glass-card {
                border-radius: var(--radius-lg);
            }

            .mac-card,
            .gitee-card,
            .material-card,
            .modern-card {
                border-radius: var(--radius-lg);
            }
        }

        @media (max-width: 480px) {
            .container {
                padding: var(--spacing-sm);
            }

            .glass-card {
                padding: var(--spacing-md);
            }

            .section-title {
                font-size: 1.25rem;
            }

            .logo-text {
                font-size: 1.5rem;
            }

            .btn-primary,
            .btn-secondary {
                padding: var(--spacing-sm) var(--spacing-md);
                font-size: 0.9rem;
            }
        }

        /* 添加更多動畫效果 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes fadeInScale {
            from {
                opacity: 0;
                transform: scale(0.9);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
        }

        .glass-card {
            animation: fadeInUp 0.6s ease-out;
        }

        .btn-primary {
            animation: fadeInScale 0.4s ease-out;
        }

        .btn-secondary {
            animation: fadeInScale 0.4s ease-out 0.1s both;
        }

        .input-field:focus {
            animation: pulse 0.3s ease-out;
        }

        /* RTL 支持 */
        [dir="rtl"] {
            text-align: right;
        }

        [dir="rtl"] .header {
            flex-direction: row-reverse;
        }

        [dir="rtl"] .logo {
            flex-direction: row-reverse;
        }

        [dir="rtl"] .section-title::after {
            margin-left: 0;
            margin-right: var(--spacing-md);
        }

        [dir="rtl"] .footer-links {
            flex-direction: row-reverse;
        }

        [dir="rtl"] .dropdown-content {
            right: auto;
            left: 0;
        }

        [dir="rtl"] .dropdown-content.show {
            opacity: 1;
            transform: translateY(0);
        }

        [dir="rtl"] .mac-stats,
        [dir="rtl"] .gitee-stats,
        [dir="rtl"] .material-stats-left {
            flex-direction: row-reverse;
        }

        [dir="rtl"] .mac-content,
        [dir="rtl"] .gitee-content,
        [dir="rtl"] .material-top {
            flex-direction: row-reverse;
        }

        [dir="rtl"] .modern-footer {
            flex-direction: row-reverse;
        }
        
        .gitee-small-icon {
            width: 28px;
            height: 28px;
            margin-right: 10px;
            fill: #c71d23;
            display: inline-block;
            vertical-align: middle;
            flex-shrink: 0;
        }
        
        .dark-mode .gitee-small-icon {
            fill: #fc8181;
        }

        /* 動畫優化 */
        @media (prefers-reduced-motion: reduce) {

            *,
            *::before,
            *::after {
                animation-duration: 0.01ms !important;
                animation-iteration-count: 1 !important;
                transition-duration: 0.01ms !important;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <header class="header">
            <div class="logo">
                <!-- <svg t="1754809639705" class="w-10 h-10 text-red-600" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9454">
                    <path d="M512 1024C229.2224 1024 0 794.7776 0 512S229.2224 0 512 0s512 229.2224 512 512-229.2224 512-512 512z m259.1488-568.8832H480.4096a25.2928 25.2928 0 0 0-25.2928 25.2928l-0.0256 63.2064c0 13.952 11.3152 25.2928 25.2672 25.2928h177.024c13.9776 0 25.2928 11.3152 25.2928 25.2672v12.6464a75.8528 75.8528 0 0 1-75.8528 75.8528H366.592a25.2928 25.2928 0 0 1-25.2672-25.2928v-240.1792a75.8528 75.8528 0 0 1 75.8272-75.8528h353.9456a25.2928 25.2928 0 0 0 25.2672-25.2928l0.0768-63.2064a25.2928 25.2928 0 0 0-25.2672-25.2928H417.152a189.6192 189.6192 0 0 0-189.6192 189.6448v353.9456c0 13.9776 11.3152 25.2928 25.2928 25.2928h372.9408a170.6496 170.6496 0 0 0 170.6496-170.6496v-145.408a25.2928 25.2928 0 0 0-25.2928-25.2672z" fill="currentColor" p-id="9455"></path>
                </svg> -->
                <h1 class="logo-text">GitCodeTree</h1>
            </div>
            <div class="flex items-center gap-2">
                <div class="dropdown">
                    <button id="languageToggle" class="theme-toggle">
                        <i class="fas fa-globe text-gray-600"></i>
                    </button>
                    <div class="dropdown-content language-dropdown">
                        <a href="#" data-lang="zh-CN" class="language-option">
                            <i class="fas fa-flag mr-2"></i>简体中文
                        </a>                        <a href="#" data-lang="en" class="language-option">
                            <i class="fas fa-flag-usa mr-2"></i>English
                        </a>
                       
                        <a href="#" data-lang="es" class="language-option">
                            <i class="fas fa-flag mr-2"></i>Español
                        </a>
                        <a href="#" data-lang="fr" class="language-option">
                            <i class="fas fa-flag mr-2"></i>Français
                        </a>
                        <a href="#" data-lang="de" class="language-option">
                            <i class="fas fa-flag mr-2"></i>Deutsch
                        </a>
                        <a href="#" data-lang="pt" class="language-option">
                            <i class="fas fa-flag mr-2"></i>Português
                        </a>
                        <a href="#" data-lang="it" class="language-option">
                            <i class="fas fa-flag mr-2"></i>Italiano
                        </a>
                        <a href="#" data-lang="nl" class="language-option">
                            <i class="fas fa-flag mr-2"></i>Nederlands
                        </a>
                        <a href="#" data-lang="ru" class="language-option">
                            <i class="fas fa-flag mr-2"></i>Русский
                        </a>
                        <a href="#" data-lang="ar" class="language-option">
                            <i class="fas fa-flag mr-2"></i>العربية
                        </a>
                    </div>
                </div>
            <button id="themeToggle" class="theme-toggle">
                <i class="fas fa-moon text-gray-600"></i>
            </button>
            </div>
        </header>
        
        <main>
            <section class="glass-card p-6 mb-6">
                <details>
                    <summary
                        class="cursor-pointer flex justify-between items-center text-lg font-semibold text-gray-700 hover:text-gray-900 transition duration-200">
                        <span><i class="fas fa-key mr-2"></i><span data-i18n="api_token_settings">API Access Token
                                Settings</span></span>
                        <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
                    </summary>
                    <div class="mt-4 space-y-4 pt-4 border-t border-gray-100">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2"
                                data-i18n="gitcode_token_label">GitCode Personal Access Token</label>
                            <div class="flex space-x-2">
                                <input type="password" id="tokenInput" data-i18n-placeholder="token_placeholder"
                                    placeholder="Enter your GitCode personal access token" class="flex-1 input-field">
                                <button id="saveTokenBtn" class="btn-secondary" data-i18n="save">Save</button>
                            </div>
                        </div>
                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <p class="text-sm text-blue-700">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong data-i18n="how_to_get_token">How to get access token:</strong><br>
                                <span data-i18n="token_instructions">Please visit</span> <a
                                    href="https://gitcode.com/setting/token-classic" target="_blank"
                                    class="font-semibold underline hover:text-blue-800"
                                    data-i18n="token_page_link">GitCode Personal Access Token page <i
                                        class="fas fa-external-link-alt text-xs"></i></a> <span
                                    data-i18n="token_instructions_2">to generate a new token, make sure to check</span>
                                <code class="bg-blue-100 px-1 rounded">user_info</code> <span data-i18n="and">and</span>
                                <code class="bg-blue-100 px-1 rounded">projects</code> <span
                                    data-i18n="permissions">permissions</span>.
                            </p>
                        </div>
                        <div id="tokenStatus" class="hidden">
                            <div class="flex items-center space-x-2 text-green-600">
                                <i class="fas fa-check-circle"></i>
                                <span class="text-sm" data-i18n="token_saved">Access token saved</span>
                            </div>
                        </div>
                    </div>
                </details>
            </section>
            
            <section class="glass-card p-6">
                <h2 class="section-title">
                    <i class="fas fa-tools mr-2"></i><span data-i18n="project_address">Project Address</span>
                </h2>
                <div class="space-y-4">
                    <input type="text" id="projectInput" data-i18n-placeholder="project_placeholder"
                        placeholder="e.g.: gitcode.com/owner/repo or owner/repo" class="w-full input-field">
                    
                    <div class="advanced-options">
                        <div class="advanced-options-title">
                            <i class="fas fa-cog mr-2"></i><span data-i18n="advanced_options">Advanced Options</span>
                        </div>
                        <div class="advanced-options-content">
                            <div class="option-group">
                                <label class="option-label" data-i18n="directory_depth">Directory Depth</label>
                                <select id="depthSelect" class="input-field">
                                    <option value="1" data-i18n="depth_1">1 level (root only)</option>
                                    <option value="2" data-i18n="depth_2">2 levels</option>
                                    <option value="3" data-i18n="depth_3">3 levels</option>
                                    <option value="4" data-i18n="depth_4">4 levels</option>
                                    <option value="5" data-i18n="depth_5">5 levels</option>
                                    <option value="0" data-i18n="depth_unlimited">All (unlimited)</option>
                                </select>
                            </div>
                            <div class="option-group">
                                <label class="option-label" data-i18n="display_content">Display Content</label>
                                <select id="viewTypeSelect" class="input-field">
                                    <option value="all" data-i18n="view_all">Complete view (files and folders)</option>
                                    <option value="folders" data-i18n="view_folders">Folders only</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
                        <button id="testApiBtn" class="btn-secondary flex items-center justify-center space-x-2">
                            <i class="fas fa-flask"></i>
                            <span data-i18n="test_api">Test API Connection</span>
                        </button>
                        <button id="generateDirBtn"
                            class="flex-1 btn-primary flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed"
                            disabled>
                            <i class="fas fa-folder-tree"></i>
                            <span data-i18n="generate_tree">Generate Directory Tree</span>
                        </button>
                        <button id="generateCardBtn"
                            class="flex-1 btn-primary flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed"
                            disabled>
                            <i class="fas fa-id-card"></i>
                            <span data-i18n="generate_card">Generate Share Card</span>
                        </button>
                    </div>
                </div>
                
                <div id="dirLoadingSection" class="hidden mt-6">
                    <div class="loader-container">
                        <div class="loader">
                            <div class="loader-circle"></div>
                            <div class="loader-circle"></div>
                            <div class="loader-circle"></div>
                        </div>
                        <div class="loader-text">
                            <span data-i18n="loading_directory">Getting project directory structure</span>
                            <div class="loader-dots">
                                <div class="loader-dot"></div>
                                <div class="loader-dot"></div>
                                <div class="loader-dot"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div id="dirResultSection" class="hidden mt-6">
                    <div class="result-container">
                        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4 gap-4">
                            <h3 class="text-lg font-semibold text-gray-700">
                                <i class="fas fa-folder-tree mr-2"></i><span data-i18n="project_directory_tree">Project
                                    Directory Tree</span>
                            </h3>
                            <div class="flex flex-wrap gap-2">
                                <button id="copyTextBtn" class="btn-secondary">
                                    <i class="fas fa-copy mr-1"></i><span data-i18n="copy_text">Copy Text</span>
                                </button>
                                <button id="copyMarkdownBtn" class="btn-secondary">
                                    <i class="fas fa-code mr-1"></i><span data-i18n="copy_markdown">Copy Markdown</span>
                                </button>
                                <button id="downloadImageBtn" class="btn-secondary">
                                    <i class="fas fa-image mr-1"></i><span data-i18n="export_image">Export Image</span>
                                </button>
                                <div class="dropdown">
                                    <button id="downloadScriptBtn" class="btn-secondary">
                                        <i class="fas fa-file-code mr-1"></i><span data-i18n="download_script">Download
                                            Script</span> <i class="fas fa-caret-down ml-1"></i>
                                    </button>
                                    <div class="dropdown-content">
                                        <a id="downloadBatBtn" href="#" data-i18n="windows_bat">Windows (.bat)</a>
                                        <a id="downloadShBtn" href="#" data-i18n="linux_mac_sh">Linux/Mac (.sh)</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div id="directoryTreeContainer" class="directory-tree-container"></div>
                    </div>
                </div>
                
                <div id="cardLoadingSection" class="hidden mt-6">
                    <div class="loader-container">
                        <div class="loader">
                            <div class="loader-circle"></div>
                            <div class="loader-circle"></div>
                            <div class="loader-circle"></div>
                        </div>
                        <div class="loader-text">
                            <span data-i18n="loading_card">Generating project share card</span>
                            <div class="loader-dots">
                                <div class="loader-dot"></div>
                                <div class="loader-dot"></div>
                                <div class="loader-dot"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div id="cardResultSection" class="hidden mt-6">
                    <div class="result-container">
                        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4 gap-4">
                            <h3 class="text-lg font-semibold text-gray-700">
                                <i class="fas fa-id-card mr-2"></i><span data-i18n="project_share_card">Project Share
                                    Card</span>
                            </h3>
                            <div class="flex flex-wrap gap-2">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1"
                                        data-i18n="card_style">Card Style</label>
                                    <select id="cardStyleSelect" class="input-field text-sm">
                                        <option value="mac" data-i18n="style_mac">macOS Style</option>
                                        <option value="gitee" data-i18n="style_gitee">GitCode Style</option>
                                        <option value="material" data-i18n="style_material">Material Style</option>
                                        <option value="modern" data-i18n="style_modern">Modern Style</option>
                                    </select>
                                </div>
                                <button id="downloadCardBtn" class="btn-secondary self-end">
                                    <i class="fas fa-download mr-1"></i><span data-i18n="download_card">Download
                                        Card</span>
                                </button>
                            </div>
                        </div>
                        <div class="flex justify-center">
                            <div id="shareCardContainer" class="w-full max-w-md"></div>
                        </div>
                    </div>
                </div>
                
                <div id="errorSection" class="hidden mt-6 bg-red-50 border border-red-200 rounded-lg p-6">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle text-red-600 text-xl mr-3"></i>
                        <div>
                            <h3 class="text-lg font-semibold text-red-800" data-i18n="fetch_failed">Fetch Failed</h3>
                            <p class="text-red-600 mt-1" id="errorMessage"></p>
                        </div>
                    </div>
                </div>
                
                <div id="successSection" class="hidden mt-6 bg-green-50 border border-green-200 rounded-lg p-6">
                    <div class="flex items-center">
                        <i class="fas fa-check-circle text-green-600 text-xl mr-3"></i>
                        <div>
                            <h3 class="text-lg font-semibold text-green-800" data-i18n="operation_success">Operation
                                Successful</h3>
                            <p class="text-green-600 mt-1" id="successMessage"></p>
                        </div>
                    </div>
                </div>
            </section>
        </main>
        
         <footer class="footer">
            <div class="footer-links">
                <a href="https://gitcode.com/nutpi/GitTree" target="_blank" class="footer-link">
                    <i class="fab fa-git-alt mr-1"></i>nutpi/GitCodeTree
                </a>
                <button id="helpBtn" class="footer-link">
                    <i class="fas fa-question-circle mr-1"></i><span data-i18n="usage_instructions">Usage
                        Instructions</span>
                </button>
            </div>
            <p>
                <i class="fas fa-code mr-2"></i>
                <a href="https://docs.gitcode.com/docs/apis/" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:text-blue-800 underline">
                    <span data-i18n="built_with">Built with GitCode API</span>
                </a> |
                <span class="text-gray-400" data-i18n="tagline">Professional · Elegant · Efficient</span>
            </p>
        </footer>
    </div>
    
    <!-- 使用说明 -->
    <div id="helpModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" data-i18n="usage_instructions">Usage Instructions</h2>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <h3>1. 获取 GitCode 访问令牌</h3>
                <p>首先，您需要获取 GitCode 的个人访问令牌（Personal Access Token）：</p>
                <ul>
                    <li>访问 <a href="https://gitcode.com/setting/token-classic" target="_blank">GitCode 个人访问令牌页面</a></li>
                    <li>点击"生成新令牌"按钮</li>
                    <li>输入令牌描述，例如"GitCodeTree"</li>
                    <li>勾选权限：<code>user_info</code> 和 <code>projects</code></li>
                    <li>点击"提交"按钮生成令牌</li>
                    <li>复制生成的令牌，粘贴到本页面的"API 访问令牌设置"中</li>
                </ul>
                
                <h3>2. 生成项目目录树</h3>
                <p>生成项目目录树的步骤：</p>
                <ul>
                    <li>在输入框中输入项目地址，格式为 <code>owner/repo</code> 或 <code>gitcode.com/owner/repo</code></li>
                    <li>根据需要调整高级选项：
                        <ul>
                            <li><strong>目录深度</strong>：控制显示的目录层级深度</li>
                            <li><strong>显示内容</strong>：选择显示完整视图（文件和文件夹）或仅文件夹</li>
                        </ul>
                    </li>
                    <li>点击"生成目录树"按钮</li>
                    <li>等待加载完成，查看生成的目录树</li>
                    <li>使用顶部按钮进行复制文本、复制Markdown、导出图片或下载脚本</li>
                </ul>
                
                <h3>3. 生成项目分享卡片</h3>
                <p>生成项目分享卡片的步骤：</p>
                <ul>
                    <li>在输入框中输入项目地址</li>
                    <li>点击"生成分享卡片"按钮</li>
                    <li>等待加载完成，查看生成的卡片</li>
                    <li>选择卡片风格（macOS、Gitee、Material 或现代风格）</li>
                    <li>点击"下载卡片"按钮保存卡片图片</li>
                </ul>
                
                <h3>4. 导出目录树图片</h3>
                <p>导出的目录树图片采用 macOS 风格设计，包含项目名称和 GitCode 图标，适合分享和展示。</p>
                
                <h3>5. 下载目录结构脚本</h3>
                <p>您可以将项目目录结构导出为脚本文件，方便在其他环境中重建相同的目录结构：</p>
                <ul>
                    <li><strong>Windows (.bat)</strong>：适用于 Windows 命令提示符</li>
                    <li><strong>Linux/Mac (.sh)</strong>：适用于 Linux 和 macOS 终端</li>
                </ul>
                
                <h3>6. 暗黑模式</h3>
                <p>点击页面右上角的主题切换按钮，可以在亮色和暗黑模式之间切换，以适应不同的使用环境。</p>
            </div>
        </div>
    </div>
    
    <script>
        // 國際化支持
        const I18n = {
            currentLang: localStorage.getItem('language') || 'en',

            translations: {
                'en': {
                    // API Token Section
                    'api_token_settings': 'API Access Token Settings',
                    'gitcode_token_label': 'GitCode Personal Access Token',
                    'token_placeholder': 'Enter your GitCode personal access token',
                    'save': 'Save',
                    'how_to_get_token': 'How to get access token:',
                    'token_instructions': 'Please visit',
                    'token_page_link': 'GitCode Personal Access Token page',
                    'token_instructions_2': 'to generate a new token, make sure to check',
                    'and': 'and',
                    'permissions': 'permissions',
                    'token_saved': 'Access token saved',

                    // Project Address Section
                    'project_address': 'Project Address',
                    'project_placeholder': 'e.g.: gitcode.com/owner/repo or owner/repo',
                    'advanced_options': 'Advanced Options',
                    'directory_depth': 'Directory Depth',
                    'depth_1': '1 level (root only)',
                    'depth_2': '2 levels',
                    'depth_3': '3 levels',
                    'depth_4': '4 levels',
                    'depth_5': '5 levels',
                    'depth_unlimited': 'All (unlimited)',
                    'display_content': 'Display Content',
                    'view_all': 'Complete view (files and folders)',
                    'view_folders': 'Folders only',
                    'test_api': 'Test API Connection',
                    'generate_tree': 'Generate Directory Tree',
                    'generate_card': 'Generate Share Card',

                    // Loading Messages
                    'loading_directory': 'Getting project directory structure',
                    'loading_card': 'Generating project share card',

                    // Results Section
                    'project_directory_tree': 'Project Directory Tree',
                    'copy_text': 'Copy Text',
                    'copy_markdown': 'Copy Markdown',
                    'export_image': 'Export Image',
                    'download_script': 'Download Script',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'Project Share Card',
                    'card_style': 'Card Style',
                    'style_mac': 'macOS Style',
                    'style_gitee': 'GitCode Style',
                    'style_material': 'Material Style',
                    'style_modern': 'Modern Style',
                    'download_card': 'Download Card',

                    // Messages
                    'fetch_failed': 'Fetch Failed',
                    'operation_success': 'Operation Successful',
                    'copied': 'Copied!',
                    'downloaded': 'Downloaded!',

                    // Footer
                    'usage_instructions': 'Usage Instructions',
                    'built_with': 'Built with GitCode API',
                    'tagline': 'Professional · Elegant · Efficient',

                    // Error Messages
                    'enter_project_address': 'Please enter project address or path',
                    'api_test_success': 'API connection test successful! Project:',
                    'api_test_failed': 'API connection test failed:',
                    'generate_image_failed': 'Failed to generate image, please try again later',
                    'generate_card_failed': 'Failed to generate card image, please try again later',
                    'please_generate_card_first': 'Please generate share card first',
                    'unexpected_error': 'Unexpected error occurred, please refresh the page and try again',
                    'request_failed': 'Request failed, please check your network connection or try again later'
                },

                'zh-CN': {
                    // API Token Section
                    'api_token_settings': 'API 访问令牌设置',
                    'gitcode_token_label': 'GitCode 个人访问令牌',
                    'token_placeholder': '输入你的 GitCode 个人访问令牌',
                    'save': '保存',
                    'how_to_get_token': '如何获取访问令牌：',
                    'token_instructions': '请访问',
                    'token_page_link': 'GitCode 个人访问令牌页面',
                    'token_instructions_2': '生成新令牌，确保勾选',
                    'and': '和',
                    'permissions': '权限',
                    'token_saved': '访问令牌已保存',

                    // Project Address Section
                    'project_address': '项目地址',
                    'project_placeholder': '例如：gitcode.com/owner/repo 或 owner/repo',
                    'advanced_options': '高级选项',
                    'directory_depth': '目录深度',
                    'depth_1': '1层（仅根目录）',
                    'depth_2': '2层',
                    'depth_3': '3层',
                    'depth_4': '4层',
                    'depth_5': '5层',
                    'depth_unlimited': '全部（无限制）',
                    'display_content': '显示内容',
                    'view_all': '完整视图（文件和文件夹）',
                    'view_folders': '仅文件夹',
                    'test_api': '测试API连接',
                    'generate_tree': '生成目录树',
                    'generate_card': '生成分享卡片',

                    // Loading Messages
                    'loading_directory': '正在获取项目目录结构',
                    'loading_card': '正在生成项目分享卡片',

                    // Results Section
                    'project_directory_tree': '项目目录树',
                    'copy_text': '复制文本',
                    'copy_markdown': '复制Markdown',
                    'export_image': '导出图片',
                    'download_script': '下载脚本',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': '项目分享卡片',
                    'card_style': '卡片风格',
                    'style_mac': 'macOS 风格',
                    'style_gitee': 'GitCode 风格',
                    'style_material': 'Material 风格',
                    'style_modern': '现代风格',
                    'download_card': '下载卡片',

                    // Messages
                    'fetch_failed': '获取失败',
                    'operation_success': '操作成功',
                    'copied': '已复制！',
                    'downloaded': '已下载！',

                    // Footer
                    'usage_instructions': '使用说明',
                    'built_with': '使用 GitCode API 构建',
                    'tagline': '专业 · 优雅 · 高效',

                    // Error Messages
                    'enter_project_address': '请输入项目地址或路径',
                    'api_test_success': 'API连接测试成功！项目：',
                    'api_test_failed': 'API连接测试失败：',
                    'generate_image_failed': '生成图片失败，请稍后重试',
                    'generate_card_failed': '生成卡片图片失败，请稍后重试',
                    'please_generate_card_first': '请先生成分享卡片',
                    'unexpected_error': '发生未预期的错误，请刷新页面重试',
                    'request_failed': '请求失败，请检查网络连接或稍后重试'
                },

                'es': {
                    // API Token Section
                    'api_token_settings': 'Configuración de Token de Acceso API',
                    'gitcode_token_label': 'Token de Acceso Personal de GitCode',
                    'token_placeholder': 'Ingresa tu token de acceso personal de GitCode',
                    'save': 'Guardar',
                    'how_to_get_token': 'Cómo obtener el token de acceso:',
                    'token_instructions': 'Por favor visita',
                    'token_page_link': 'la página de Token de Acceso Personal de GitCode',
                    'token_instructions_2': 'para generar un nuevo token, asegúrate de marcar',
                    'and': 'y',
                    'permissions': 'permisos',
                    'token_saved': 'Token de acceso guardado',

                    // Project Address Section
                    'project_address': 'Dirección del Proyecto',
                    'project_placeholder': 'ej.: gitcode.com/owner/repo o owner/repo',
                    'advanced_options': 'Opciones Avanzadas',
                    'directory_depth': 'Profundidad del Directorio',
                    'depth_1': '1 nivel (solo raíz)',
                    'depth_2': '2 niveles',
                    'depth_3': '3 niveles',
                    'depth_4': '4 niveles',
                    'depth_5': '5 niveles',
                    'depth_unlimited': 'Todos (ilimitado)',
                    'display_content': 'Contenido a Mostrar',
                    'view_all': 'Vista completa (archivos y carpetas)',
                    'view_folders': 'Solo carpetas',
                    'test_api': 'Probar Conexión API',
                    'generate_tree': 'Generar Árbol de Directorios',
                    'generate_card': 'Generar Tarjeta de Compartir',

                    // Loading Messages
                    'loading_directory': 'Obteniendo estructura de directorios del proyecto',
                    'loading_card': 'Generando tarjeta de compartir del proyecto',

                    // Results Section
                    'project_directory_tree': 'Árbol de Directorios del Proyecto',
                    'copy_text': 'Copiar Texto',
                    'copy_markdown': 'Copiar Markdown',
                    'export_image': 'Exportar Imagen',
                    'download_script': 'Descargar Script',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'Tarjeta de Compartir del Proyecto',
                    'card_style': 'Estilo de Tarjeta',
                    'style_mac': 'Estilo macOS',
                    'style_gitee': 'Estilo GitCode',
                    'style_material': 'Estilo Material',
                    'style_modern': 'Estilo Moderno',
                    'download_card': 'Descargar Tarjeta',

                    // Messages
                    'fetch_failed': 'Error al Obtener',
                    'operation_success': 'Operación Exitosa',
                    'copied': '¡Copiado!',
                    'downloaded': '¡Descargado!',

                    // Footer
                    'usage_instructions': 'Instrucciones de Uso',
                    'built_with': 'Construido con GitCode API',
                    'tagline': 'Profesional · Elegante · Eficiente',

                    // Error Messages
                    'enter_project_address': 'Por favor ingresa la dirección o ruta del proyecto',
                    'api_test_success': '¡Prueba de conexión API exitosa! Proyecto:',
                    'api_test_failed': 'Prueba de conexión API falló:',
                    'generate_image_failed': 'Error al generar imagen, por favor intenta más tarde',
                    'generate_card_failed': 'Error al generar imagen de tarjeta, por favor intenta más tarde',
                    'please_generate_card_first': 'Por favor genera primero la tarjeta de compartir',
                    'unexpected_error': 'Ocurrió un error inesperado, por favor actualiza la página e intenta de nuevo',
                    'request_failed': 'Solicitud falló, por favor verifica tu conexión de red o intenta más tarde'
                },

                'fr': {
                    // API Token Section
                    'api_token_settings': 'Paramètres du Token d\'Accès API',
                    'gitcode_token_label': 'Token d\'Accès Personnel GitCode',
                    'token_placeholder': 'Entrez votre token d\'accès personnel GitCode',
                    'save': 'Enregistrer',
                    'how_to_get_token': 'Comment obtenir le token d\'accès :',
                    'token_instructions': 'Veuillez visiter',
                    'token_page_link': 'la page Token d\'Accès Personnel GitCode',
                    'token_instructions_2': 'pour générer un nouveau token, assurez-vous de cocher',
                    'and': 'et',
                    'permissions': 'permissions',
                    'token_saved': 'Token d\'accès enregistré',

                    // Project Address Section
                    'project_address': 'Adresse du Projet',
                    'project_placeholder': 'ex.: gitcode.com/owner/repo ou owner/repo',
                    'advanced_options': 'Options Avancées',
                    'directory_depth': 'Profondeur du Répertoire',
                    'depth_1': '1 niveau (racine seulement)',
                    'depth_2': '2 niveaux',
                    'depth_3': '3 niveaux',
                    'depth_4': '4 niveaux',
                    'depth_5': '5 niveaux',
                    'depth_unlimited': 'Tous (illimité)',
                    'display_content': 'Contenu à Afficher',
                    'view_all': 'Vue complète (fichiers et dossiers)',
                    'view_folders': 'Dossiers seulement',
                    'test_api': 'Tester la Connexion API',
                    'generate_tree': 'Générer l\'Arbre de Répertoires',
                    'generate_card': 'Générer la Carte de Partage',

                    // Loading Messages
                    'loading_directory': 'Obtention de la structure de répertoires du projet',
                    'loading_card': 'Génération de la carte de partage du projet',

                    // Results Section
                    'project_directory_tree': 'Arbre de Répertoires du Projet',
                    'copy_text': 'Copier le Texte',
                    'copy_markdown': 'Copier Markdown',
                    'export_image': 'Exporter l\'Image',
                    'download_script': 'Télécharger le Script',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'Carte de Partage du Projet',
                    'card_style': 'Style de Carte',
                    'style_mac': 'Style macOS',
                    'style_gitee': 'Style GitCode',
                    'style_material': 'Style Material',
                    'style_modern': 'Style Moderne',
                    'download_card': 'Télécharger la Carte',

                    // Messages
                    'fetch_failed': 'Échec de la Récupération',
                    'operation_success': 'Opération Réussie',
                    'copied': 'Copié !',
                    'downloaded': 'Téléchargé !',

                    // Footer
                    'usage_instructions': 'Instructions d\'Utilisation',
                    'built_with': 'Construit avec GitCode API',
                    'tagline': 'Professionnel · Élégant · Efficace',

                    // Error Messages
                    'enter_project_address': 'Veuillez entrer l\'adresse ou le chemin du projet',
                    'api_test_success': 'Test de connexion API réussi ! Projet :',
                    'api_test_failed': 'Test de connexion API échoué :',
                    'generate_image_failed': 'Échec de génération d\'image, veuillez réessayer plus tard',
                    'generate_card_failed': 'Échec de génération d\'image de carte, veuillez réessayer plus tard',
                    'please_generate_card_first': 'Veuillez d\'abord générer la carte de partage',
                    'unexpected_error': 'Une erreur inattendue s\'est produite, veuillez actualiser la page et réessayer',
                    'request_failed': 'Échec de la requête, veuillez vérifier votre connexion réseau ou réessayer plus tard'
                },

                'de': {
                    // API Token Section
                    'api_token_settings': 'API-Zugriffstoken-Einstellungen',
                    'gitcode_token_label': 'GitCode Personal Access Token',
                    'token_placeholder': 'Geben Sie Ihren GitCode Personal Access Token ein',
                    'save': 'Speichern',
                    'how_to_get_token': 'So erhalten Sie den Zugriffstoken:',
                    'token_instructions': 'Bitte besuchen Sie',
                    'token_page_link': 'die GitCode Personal Access Token Seite',
                    'token_instructions_2': 'um einen neuen Token zu generieren, stellen Sie sicher, dass Sie',
                    'and': 'und',
                    'permissions': 'Berechtigungen',
                    'token_saved': 'Zugriffstoken gespeichert',

                    // Project Address Section
                    'project_address': 'Projektadresse',
                    'project_placeholder': 'z.B.: gitcode.com/owner/repo oder owner/repo',
                    'advanced_options': 'Erweiterte Optionen',
                    'directory_depth': 'Verzeichnistiefe',
                    'depth_1': '1 Ebene (nur Root)',
                    'depth_2': '2 Ebenen',
                    'depth_3': '3 Ebenen',
                    'depth_4': '4 Ebenen',
                    'depth_5': '5 Ebenen',
                    'depth_unlimited': 'Alle (unbegrenzt)',
                    'display_content': 'Anzuzeigender Inhalt',
                    'view_all': 'Vollansicht (Dateien und Ordner)',
                    'view_folders': 'Nur Ordner',
                    'test_api': 'API-Verbindung testen',
                    'generate_tree': 'Verzeichnisbaum generieren',
                    'generate_card': 'Teilungskarte generieren',

                    // Loading Messages
                    'loading_directory': 'Projektverzeichnisstruktur wird abgerufen',
                    'loading_card': 'Projekt-Teilungskarte wird generiert',

                    // Results Section
                    'project_directory_tree': 'Projektverzeichnisbaum',
                    'copy_text': 'Text kopieren',
                    'copy_markdown': 'Markdown kopieren',
                    'export_image': 'Bild exportieren',
                    'download_script': 'Script herunterladen',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'Projekt-Teilungskarte',
                    'card_style': 'Kartenstil',
                    'style_mac': 'macOS Stil',
                    'style_gitee': 'GitCode Stil',
                    'style_material': 'Material Stil',
                    'style_modern': 'Moderner Stil',
                    'download_card': 'Karte herunterladen',

                    // Messages
                    'fetch_failed': 'Abruf fehlgeschlagen',
                    'operation_success': 'Operation erfolgreich',
                    'copied': 'Kopiert!',
                    'downloaded': 'Heruntergeladen!',

                    // Footer
                    'usage_instructions': 'Anweisungen zur Verwendung',
                    'built_with': 'Erstellt mit GitCode API',
                    'tagline': 'Professionell · Elegant · Effizient',

                    // Error Messages
                    'enter_project_address': 'Bitte geben Sie die Projektadresse oder den Pfad ein',
                    'api_test_success': 'API-Verbindungstest erfolgreich! Projekt:',
                    'api_test_failed': 'API-Verbindungstest fehlgeschlagen:',
                    'generate_image_failed': 'Bildgenerierung fehlgeschlagen, bitte versuchen Sie es später erneut',
                    'generate_card_failed': 'Kartenbildgenerierung fehlgeschlagen, bitte versuchen Sie es später erneut',
                    'please_generate_card_first': 'Bitte generieren Sie zuerst die Teilungskarte',
                    'unexpected_error': 'Ein unerwarteter Fehler ist aufgetreten, bitte aktualisieren Sie die Seite und versuchen Sie es erneut',
                    'request_failed': 'Anfrage fehlgeschlagen, bitte überprüfen Sie Ihre Netzwerkverbindung oder versuchen Sie es später erneut'
                },

                'pt': {
                    // API Token Section
                    'api_token_settings': 'Configurações do Token de Acesso API',
                    'gitcode_token_label': 'Token de Acesso Pessoal GitCode',
                    'token_placeholder': 'Digite seu token de acesso pessoal GitCode',
                    'save': 'Salvar',
                    'how_to_get_token': 'Como obter o token de acesso:',
                    'token_instructions': 'Por favor visite',
                    'token_page_link': 'a página de Token de Acesso Pessoal GitCode',
                    'token_instructions_2': 'para gerar um novo token, certifique-se de marcar',
                    'and': 'e',
                    'permissions': 'permissões',
                    'token_saved': 'Token de acesso salvo',

                    // Project Address Section
                    'project_address': 'Endereço do Projeto',
                    'project_placeholder': 'ex.: gitcode.com/owner/repo ou owner/repo',
                    'advanced_options': 'Opções Avançadas',
                    'directory_depth': 'Profundidade do Diretório',
                    'depth_1': '1 nível (apenas raiz)',
                    'depth_2': '2 níveis',
                    'depth_3': '3 níveis',
                    'depth_4': '4 níveis',
                    'depth_5': '5 níveis',
                    'depth_unlimited': 'Todos (ilimitado)',
                    'display_content': 'Conteúdo para Exibir',
                    'view_all': 'Visualização completa (arquivos e pastas)',
                    'view_folders': 'Apenas pastas',
                    'test_api': 'Testar Conexão API',
                    'generate_tree': 'Gerar Árvore de Diretórios',
                    'generate_card': 'Gerar Cartão de Compartilhamento',

                    // Loading Messages
                    'loading_directory': 'Obtendo estrutura de diretórios do projeto',
                    'loading_card': 'Gerando cartão de compartilhamento do projeto',

                    // Results Section
                    'project_directory_tree': 'Árvore de Diretórios do Projeto',
                    'copy_text': 'Copiar Texto',
                    'copy_markdown': 'Copiar Markdown',
                    'export_image': 'Exportar Imagem',
                    'download_script': 'Baixar Script',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'Cartão de Compartilhamento do Projeto',
                    'card_style': 'Estilo do Cartão',
                    'style_mac': 'Estilo macOS',
                    'style_gitee': 'Estilo GitCode',
                    'style_material': 'Estilo Material',
                    'style_modern': 'Estilo Moderno',
                    'download_card': 'Baixar Cartão',

                    // Messages
                    'fetch_failed': 'Falha na Busca',
                    'operation_success': 'Operação Bem-sucedida',
                    'copied': 'Copiado!',
                    'downloaded': 'Baixado!',

                    // Footer
                    'usage_instructions': 'Instruções de Uso',
                    'built_with': 'Construído com GitCode API',
                    'tagline': 'Profissional · Elegante · Eficiente',

                    // Error Messages
                    'enter_project_address': 'Por favor, digite o endereço ou caminho do projeto',
                    'api_test_success': 'Teste de conexão API bem-sucedido! Projeto:',
                    'api_test_failed': 'Teste de conexão API falhou:',
                    'generate_image_failed': 'Falha ao gerar imagem, tente novamente mais tarde',
                    'generate_card_failed': 'Falha ao gerar imagem do cartão, tente novamente mais tarde',
                    'please_generate_card_first': 'Por favor, gere primeiro o cartão de compartilhamento',
                    'unexpected_error': 'Ocorreu um erro inesperado, atualize a página e tente novamente',
                    'request_failed': 'Falha na solicitação, verifique sua conexão de rede ou tente novamente mais tarde'
                },

                'it': {
                    // API Token Section
                    'api_token_settings': 'Impostazioni Token di Accesso API',
                    'gitcode_token_label': 'Token di Accesso Personale GitCode',
                    'token_placeholder': 'Inserisci il tuo token di accesso personale GitCode',
                    'save': 'Salva',
                    'how_to_get_token': 'Come ottenere il token di accesso:',
                    'token_instructions': 'Per favore visita',
                    'token_page_link': 'la pagina Token di Accesso Personale GitCode',
                    'token_instructions_2': 'per generare un nuovo token, assicurati di spuntare',
                    'and': 'e',
                    'permissions': 'permessi',
                    'token_saved': 'Token di accesso salvato',

                    // Project Address Section
                    'project_address': 'Indirizzo del Progetto',
                    'project_placeholder': 'es.: gitcode.com/owner/repo o owner/repo',
                    'advanced_options': 'Opzioni Avanzate',
                    'directory_depth': 'Profondità Directory',
                    'depth_1': '1 livello (solo root)',
                    'depth_2': '2 livelli',
                    'depth_3': '3 livelli',
                    'depth_4': '4 livelli',
                    'depth_5': '5 livelli',
                    'depth_unlimited': 'Tutti (illimitato)',
                    'display_content': 'Contenuto da Visualizzare',
                    'view_all': 'Vista completa (file e cartelle)',
                    'view_folders': 'Solo cartelle',
                    'test_api': 'Testa Connessione API',
                    'generate_tree': 'Genera Albero Directory',
                    'generate_card': 'Genera Card di Condivisione',

                    // Loading Messages
                    'loading_directory': 'Recupero struttura directory del progetto',
                    'loading_card': 'Generazione card di condivisione del progetto',

                    // Results Section
                    'project_directory_tree': 'Albero Directory del Progetto',
                    'copy_text': 'Copia Testo',
                    'copy_markdown': 'Copia Markdown',
                    'export_image': 'Esporta Immagine',
                    'download_script': 'Scarica Script',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'Card di Condivisione del Progetto',
                    'card_style': 'Stile Card',
                    'style_mac': 'Stile macOS',
                    'style_gitee': 'Stile GitCode',
                    'style_material': 'Stile Material',
                    'style_modern': 'Stile Moderno',
                    'download_card': 'Scarica Card',

                    // Messages
                    'fetch_failed': 'Recupero Fallito',
                    'operation_success': 'Operazione Riuscita',
                    'copied': 'Copiato!',
                    'downloaded': 'Scaricato!',

                    // Footer
                    'usage_instructions': 'Istruzioni per l\'Uso',
                    'built_with': 'Costruito con GitCode API',
                    'tagline': 'Professionale · Elegante · Efficiente',

                    // Error Messages
                    'enter_project_address': 'Per favore inserisci l\'indirizzo o il percorso del progetto',
                    'api_test_success': 'Test connessione API riuscito! Progetto:',
                    'api_test_failed': 'Test connessione API fallito:',
                    'generate_image_failed': 'Generazione immagine fallita, riprova più tardi',
                    'generate_card_failed': 'Generazione immagine card fallita, riprova più tardi',
                    'please_generate_card_first': 'Per favore genera prima la card di condivisione',
                    'unexpected_error': 'Si è verificato un errore imprevisto, aggiorna la pagina e riprova',
                    'request_failed': 'Richiesta fallita, controlla la tua connessione di rete o riprova più tardi'
                },

                'nl': {
                    // API Token Section
                    'api_token_settings': 'API Toegangstoken Instellingen',
                    'gitcode_token_label': 'GitCode Persoonlijk Toegangstoken',
                    'token_placeholder': 'Voer je GitCode persoonlijk toegangstoken in',
                    'save': 'Opslaan',
                    'how_to_get_token': 'Hoe toegangstoken te krijgen:',
                    'token_instructions': 'Bezoek',
                    'token_page_link': 'de GitCode Persoonlijk Toegangstoken pagina',
                    'token_instructions_2': 'om een nieuw token te genereren, zorg ervoor dat je',
                    'and': 'en',
                    'permissions': 'machtigingen',
                    'token_saved': 'Toegangstoken opgeslagen',

                    // Project Address Section
                    'project_address': 'Project Adres',
                    'project_placeholder': 'bijv.: gitcode.com/owner/repo of owner/repo',
                    'advanced_options': 'Geavanceerde Opties',
                    'directory_depth': 'Map Diepte',
                    'depth_1': '1 niveau (alleen root)',
                    'depth_2': '2 niveaus',
                    'depth_3': '3 niveaus',
                    'depth_4': '4 niveaus',
                    'depth_5': '5 niveaus',
                    'depth_unlimited': 'Alle (onbeperkt)',
                    'display_content': 'Weer te Geven Inhoud',
                    'view_all': 'Volledige weergave (bestanden en mappen)',
                    'view_folders': 'Alleen mappen',
                    'test_api': 'Test API Verbinding',
                    'generate_tree': 'Genereer Mapstructuur',
                    'generate_card': 'Genereer Deelkaart',

                    // Loading Messages
                    'loading_directory': 'Project mapstructuur ophalen',
                    'loading_card': 'Project deelkaart genereren',

                    // Results Section
                    'project_directory_tree': 'Project Mapstructuur',
                    'copy_text': 'Kopieer Tekst',
                    'copy_markdown': 'Kopieer Markdown',
                    'export_image': 'Exporteer Afbeelding',
                    'download_script': 'Download Script',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'Project Deelkaart',
                    'card_style': 'Kaart Stijl',
                    'style_mac': 'macOS Stijl',
                    'style_gitee': 'GitCode Stijl',
                    'style_material': 'Material Stijl',
                    'style_modern': 'Moderne Stijl',
                    'download_card': 'Download Kaart',

                    // Messages
                    'fetch_failed': 'Ophalen Mislukt',
                    'operation_success': 'Operatie Succesvol',
                    'copied': 'Gekopieerd!',
                    'downloaded': 'Gedownload!',

                    // Footer
                    'usage_instructions': 'Gebruiksinstructies',
                    'built_with': 'Gebouwd met GitCode API',
                    'tagline': 'Professioneel · Elegant · Efficiënt',

                    // Error Messages
                    'enter_project_address': 'Voer het projectadres of pad in',
                    'api_test_success': 'API verbindingstest succesvol! Project:',
                    'api_test_failed': 'API verbindingstest mislukt:',
                    'generate_image_failed': 'Afbeelding genereren mislukt, probeer het later opnieuw',
                    'generate_card_failed': 'Kaartafbeelding genereren mislukt, probeer het later opnieuw',
                    'please_generate_card_first': 'Genereer eerst de deelkaart',
                    'unexpected_error': 'Er is een onverwachte fout opgetreden, ververs de pagina en probeer opnieuw',
                    'request_failed': 'Verzoek mislukt, controleer je netwerkverbinding of probeer het later opnieuw'
                },

                'ru': {
                    // API Token Section
                    'api_token_settings': 'Настройки токена доступа API',
                    'gitcode_token_label': 'Личный токен доступа GitCode',
                    'token_placeholder': 'Введите ваш личный токен доступа GitCode',
                    'save': 'Сохранить',
                    'how_to_get_token': 'Как получить токен доступа:',
                    'token_instructions': 'Пожалуйста, посетите',
                    'token_page_link': 'страницу личного токена доступа GitCode',
                    'token_instructions_2': 'чтобы сгенерировать новый токен, убедитесь, что отметили',
                    'and': 'и',
                    'permissions': 'разрешения',
                    'token_saved': 'Токен доступа сохранен',

                    // Project Address Section
                    'project_address': 'Адрес проекта',
                    'project_placeholder': 'напр.: gitcode.com/owner/repo или owner/repo',
                    'advanced_options': 'Дополнительные опции',
                    'directory_depth': 'Глубина каталога',
                    'depth_1': '1 уровень (только корень)',
                    'depth_2': '2 уровня',
                    'depth_3': '3 уровня',
                    'depth_4': '4 уровня',
                    'depth_5': '5 уровней',
                    'depth_unlimited': 'Все (без ограничений)',
                    'display_content': 'Отображаемое содержимое',
                    'view_all': 'Полный вид (файлы и папки)',
                    'view_folders': 'Только папки',
                    'test_api': 'Тест подключения API',
                    'generate_tree': 'Сгенерировать дерево каталогов',
                    'generate_card': 'Сгенерировать карточку для обмена',

                    // Loading Messages
                    'loading_directory': 'Получение структуры каталогов проекта',
                    'loading_card': 'Генерация карточки для обмена проекта',

                    // Results Section
                    'project_directory_tree': 'Дерево каталогов проекта',
                    'copy_text': 'Копировать текст',
                    'copy_markdown': 'Копировать Markdown',
                    'export_image': 'Экспортировать изображение',
                    'download_script': 'Скачать скрипт',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'Карточка для обмена проекта',
                    'card_style': 'Стиль карточки',
                    'style_mac': 'Стиль macOS',
                    'style_gitee': 'Стиль GitCode',
                    'style_material': 'Material стиль',
                    'style_modern': 'Современный стиль',
                    'download_card': 'Скачать карточку',

                    // Messages
                    'fetch_failed': 'Ошибка получения',
                    'operation_success': 'Операция успешна',
                    'copied': 'Скопировано!',
                    'downloaded': 'Скачано!',

                    // Footer
                    'usage_instructions': 'Инструкции по использованию',
                    'built_with': 'Создано с GitCode API',
                    'tagline': 'Профессионально · Элегантно · Эффективно',

                    // Error Messages
                    'enter_project_address': 'Пожалуйста, введите адрес или путь проекта',
                    'api_test_success': 'Тест подключения API успешен! Проект:',
                    'api_test_failed': 'Тест подключения API не удался:',
                    'generate_image_failed': 'Не удалось сгенерировать изображение, попробуйте позже',
                    'generate_card_failed': 'Не удалось сгенерировать изображение карточки, попробуйте позже',
                    'please_generate_card_first': 'Пожалуйста, сначала сгенерируйте карточку для обмена',
                    'unexpected_error': 'Произошла неожиданная ошибка, обновите страницу и попробуйте снова',
                    'request_failed': 'Запрос не удался, проверьте подключение к сети или попробуйте позже'
                },

                'ar': {
                    // API Token Section
                    'api_token_settings': 'إعدادات رمز الوصول API',
                    'gitcode_token_label': 'رمز الوصول الشخصي GitCode',
                    'token_placeholder': 'أدخل رمز الوصول الشخصي GitCode الخاص بك',
                    'save': 'حفظ',
                    'how_to_get_token': 'كيفية الحصول على رمز الوصول:',
                    'token_instructions': 'يرجى زيارة',
                    'token_page_link': 'صفحة رمز الوصول الشخصي GitCode',
                    'token_instructions_2': 'لتوليد رمز جديد، تأكد من تحديد',
                    'and': 'و',
                    'permissions': 'الأذونات',
                    'token_saved': 'تم حفظ رمز الوصول',

                    // Project Address Section
                    'project_address': 'عنوان المشروع',
                    'project_placeholder': 'مثال: gitcode.com/owner/repo أو owner/repo',
                    'advanced_options': 'خيارات متقدمة',
                    'directory_depth': 'عمق المجلد',
                    'depth_1': 'مستوى واحد (الجذر فقط)',
                    'depth_2': 'مستويان',
                    'depth_3': 'ثلاثة مستويات',
                    'depth_4': 'أربعة مستويات',
                    'depth_5': 'خمسة مستويات',
                    'depth_unlimited': 'الكل (غير محدود)',
                    'display_content': 'المحتوى المراد عرضه',
                    'view_all': 'عرض كامل (الملفات والمجلدات)',
                    'view_folders': 'المجلدات فقط',
                    'test_api': 'اختبار اتصال API',
                    'generate_tree': 'توليد شجرة المجلدات',
                    'generate_card': 'توليد بطاقة المشاركة',

                    // Loading Messages
                    'loading_directory': 'جاري الحصول على هيكل مجلدات المشروع',
                    'loading_card': 'جاري توليد بطاقة مشاركة المشروع',

                    // Results Section
                    'project_directory_tree': 'شجرة مجلدات المشروع',
                    'copy_text': 'نسخ النص',
                    'copy_markdown': 'نسخ Markdown',
                    'export_image': 'تصدير الصورة',
                    'download_script': 'تحميل السكريبت',
                    'windows_bat': 'Windows (.bat)',
                    'linux_mac_sh': 'Linux/Mac (.sh)',
                    'project_share_card': 'بطاقة مشاركة المشروع',
                    'card_style': 'نمط البطاقة',
                    'style_mac': 'نمط macOS',
                    'style_gitee': 'نمط GitCode',
                    'style_material': 'نمط Material',
                    'style_modern': 'نمط حديث',
                    'download_card': 'تحميل البطاقة',

                    // Messages
                    'fetch_failed': 'فشل في الاسترجاع',
                    'operation_success': 'تمت العملية بنجاح',
                    'copied': 'تم النسخ!',
                    'downloaded': 'تم التحميل!',

                    // Footer
                    'usage_instructions': 'تعليمات الاستخدام',
                    'built_with': 'مبني باستخدام GitCode API',
                    'tagline': 'مهني · أنيق · فعال',

                    // Error Messages
                    'enter_project_address': 'يرجى إدخال عنوان أو مسار المشروع',
                    'api_test_success': 'نجح اختبار اتصال API! المشروع:',
                    'api_test_failed': 'فشل اختبار اتصال API:',
                    'generate_image_failed': 'فشل في توليد الصورة، يرجى المحاولة لاحقاً',
                    'generate_card_failed': 'فشل في توليد صورة البطاقة، يرجى المحاولة لاحقاً',
                    'please_generate_card_first': 'يرجى توليد بطاقة المشاركة أولاً',
                    'unexpected_error': 'حدث خطأ غير متوقع، يرجى تحديث الصفحة والمحاولة مرة أخرى',
                    'request_failed': 'فشل الطلب، يرجى التحقق من اتصال الشبكة أو المحاولة لاحقاً'
                }
            },

            // 獲取翻譯文本
            t(key) {
                return this.translations[this.currentLang]?.[key] || key;
            },

            // 設置語言
            setLanguage(lang) {
                this.currentLang = lang;
                localStorage.setItem('language', lang);
                document.documentElement.lang = lang;
                
                // 設置RTL支持
                if (lang === 'ar') {
                    document.documentElement.dir = 'rtl';
                } else {
                    document.documentElement.dir = 'ltr';
                }
                
                this.updateUI();
            },

            // 更新UI文本
            updateUI() {
                // 更新所有帶有 data-i18n 屬性的元素
                document.querySelectorAll('[data-i18n]').forEach(element => {
                    const key = element.getAttribute('data-i18n');
                    const text = this.t(key);
                    if (text !== key) {
                        element.textContent = text;
                    }
                });

                // 更新所有帶有 data-i18n-placeholder 屬性的元素
                document.querySelectorAll('[data-i18n-placeholder]').forEach(element => {
                    const key = element.getAttribute('data-i18n-placeholder');
                    const text = this.t(key);
                    if (text !== key) {
                        element.placeholder = text;
                    }
                });
            }
        };

        // 應用狀態管理
        const AppState = {
            savedToken: localStorage.getItem('gitcode_token') || '',
            isDarkMode: localStorage.getItem('dark_mode') === 'true',
            selectedCardStyle: 'mac',
            currentDirectoryTree: '',
            currentProjectInfo: null,
            currentDirectoryItems: [],
            fullDirectoryTree: '',

            // 狀態更新方法
            updateToken(token) {
                this.savedToken = token;
                localStorage.setItem('gitcode_token', token);
            },

            updateDarkMode(isDark) {
                this.isDarkMode = isDark;
                localStorage.setItem('dark_mode', isDark);
            },

            updateCardStyle(style) {
                this.selectedCardStyle = style;
            },

            resetProjectData() {
                this.currentDirectoryTree = '';
                this.currentProjectInfo = null;
                this.currentDirectoryItems = [];
                this.fullDirectoryTree = '';
            }
        };

        // 工具函數
        const Utils = {
            // 顯示/隱藏元素
            showElement(elementId) {
                const element = document.getElementById(elementId);
                if (element) element.classList.remove('hidden');
            },

            hideElement(elementId) {
                const element = document.getElementById(elementId);
                if (element) element.classList.add('hidden');
            },

            // 顯示錯誤信息
            showError(message) {
                document.getElementById('errorMessage').textContent = message;
                this.hideElement('dirLoadingSection');
                this.hideElement('cardLoadingSection');
                this.hideElement('dirResultSection');
                this.hideElement('cardResultSection');
                this.hideElement('successSection');
                this.showElement('errorSection');
            },

            // 顯示成功信息
            showSuccess(message) {
                document.getElementById('successMessage').textContent = message;
                this.hideElement('dirLoadingSection');
                this.hideElement('cardLoadingSection');
                this.hideElement('dirResultSection');
                this.hideElement('cardResultSection');
                this.hideElement('errorSection');
                this.showElement('successSection');
            },

            // 按鈕反饋動畫
            showButtonFeedback(button, text = null) {
                const originalContent = button.innerHTML;
                const feedbackText = text || I18n.t('copied');
                button.innerHTML = `<i class="fas fa-check mr-1"></i>${feedbackText}`;
                button.disabled = true;

                setTimeout(() => {
                    button.innerHTML = originalContent;
                    button.disabled = false;
                }, 1500);
            },

            // 防抖函數
            debounce(func, wait) {
                let timeout;
                return function executedFunction(...args) {
                    const later = () => {
                        clearTimeout(timeout);
                        func(...args);
                    };
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                };
            }
        };

        // 檢查 QRCode 庫是否加載
        function checkQRCodeLibrary() {
            if (typeof QRCode === 'undefined') {
                console.warn('QRCode 庫未加載，嘗試重新加載...');
                // 如果 QRCode 未加載，動態加載
                const script = document.createElement('script');
                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js';
                script.onload = () => {
                    console.log('QRCode 庫加載成功');
                };
                script.onerror = () => {
                    console.error('QRCode 庫加載失敗');
                };
                document.head.appendChild(script);
                return false;
            }
            return true;
        }

        // 調試函數
        function debugQRCode() {
            console.log('=== QRCode 調試信息 ===');
            console.log('QRCode 類型:', typeof QRCode);
            console.log('QRCode 是否為函數:', typeof QRCode === 'function');
            console.log('window.QRCode:', window.QRCode);
            console.log('QRCode.CorrectLevel:', typeof QRCode !== 'undefined' ? QRCode.CorrectLevel : 'undefined');

            // 測試二維碼生成
            if (typeof QRCode !== 'undefined') {
                try {
                    const testDiv = document.createElement('div');
                    testDiv.style.width = '50px';
                    testDiv.style.height = '50px';
                    testDiv.style.border = '1px solid red';
                    document.body.appendChild(testDiv);

                    const code = new QRCode(testDiv, {
                        text: 'https://test.com',
                        width: 50,
                        height: 50
                    });

                    console.log('QRCode 測試成功', code);
                    setTimeout(() => document.body.removeChild(testDiv), 2000);
                } catch (error) {
                    console.error('QRCode 測試失敗:', error);
                }
            }
        }

        // 檢查QRCode庫加載狀態
        function checkQRCodeStatus() {
            console.log('=== QRCode 庫狀態檢查 ===');
            console.log('QRCode 類型:', typeof QRCode);
            console.log('QRCode 是否為函數:', typeof QRCode === 'function');
            console.log('window.QRCode:', window.QRCode);

            if (typeof QRCode === 'undefined') {
                console.warn('QRCode 庫未加載，嘗試動態加載...');

                // 動態加載QRCode庫
                const script = document.createElement('script');
                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js';
                script.onload = () => {
                    console.log('QRCode 庫動態加載成功');
                };
                script.onerror = () => {
                    console.error('QRCode 庫動態加載失敗');
                };
                document.head.appendChild(script);
            } else {
                console.log('QRCode 庫已加載');
            }
        }

        // 初始化應用
        window.addEventListener('DOMContentLoaded', () => {
            // 立即檢查QRCode庫狀態
            checkQRCodeStatus();

            initializeApp();

            // 添加調試按鈕（僅在開發環境）
            if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                const debugBtn = document.createElement('button');
                debugBtn.textContent = 'Debug QRCode';
                debugBtn.style.position = 'fixed';
                debugBtn.style.top = '10px';
                debugBtn.style.right = '10px';
                debugBtn.style.zIndex = '9999';
                debugBtn.style.padding = '5px 10px';
                debugBtn.style.background = '#f56565';
                debugBtn.style.color = 'white';
                debugBtn.style.border = 'none';
                debugBtn.style.borderRadius = '4px';
                debugBtn.style.cursor = 'pointer';
                debugBtn.onclick = debugQRCode;
                document.body.appendChild(debugBtn);
            }
        });

        function initializeApp() {
            // 初始化語言設置
            I18n.updateUI();

            // 初始化令牌狀態
            if (AppState.savedToken) {
                document.getElementById('tokenInput').value = AppState.savedToken;
                Utils.showElement('tokenStatus');
                document.getElementById('generateDirBtn').disabled = false;
                document.getElementById('generateCardBtn').disabled = false;
            }

            // 初始化暗黑模式
            if (AppState.isDarkMode) {
                document.body.classList.add('dark-mode');
                document.getElementById('themeToggle').innerHTML = '<i class="fas fa-sun text-gray-300"></i>';
            }

            // 綁定事件監聽器
            bindEventListeners();
        }

        // 事件監聽器綁定
        function bindEventListeners() {
            // 語言切換
            document.querySelectorAll('.language-option').forEach(option => {
                option.addEventListener('click', (e) => {
                    e.preventDefault();
                    const lang = e.target.closest('[data-lang]').getAttribute('data-lang');
                    I18n.setLanguage(lang);
                    
                    // 隱藏下拉菜單（帶動畫）
                    const dropdown = document.querySelector('.dropdown-content');
                    if (dropdown && dropdown.classList.contains('show')) {
                        dropdown.classList.remove('show');
                        setTimeout(() => {
                            dropdown.style.display = 'none';
                        }, 200);
                    }
                });
            });

            // 語言按鈕點擊事件
            const languageToggle = document.getElementById('languageToggle');
            const dropdownContent = document.querySelector('.dropdown-content');
            
            if (languageToggle && dropdownContent) {
                languageToggle.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const isVisible = dropdownContent.classList.contains('show');
                    
                    if (isVisible) {
                        // 隱藏下拉菜單
                        dropdownContent.classList.remove('show');
                        setTimeout(() => {
                            dropdownContent.style.display = 'none';
                        }, 200);
                    } else {
                        // 顯示下拉菜單
                        dropdownContent.style.display = 'block';
                        // 強制重繪以觸發動畫
                        dropdownContent.offsetHeight;
                        dropdownContent.classList.add('show');
                    }
                });

                // 點擊外部關閉下拉菜單
                document.addEventListener('click', (e) => {
                    if (!languageToggle.contains(e.target) && !dropdownContent.contains(e.target)) {
                        if (dropdownContent.classList.contains('show')) {
                            dropdownContent.classList.remove('show');
                            setTimeout(() => {
                                dropdownContent.style.display = 'none';
                            }, 200);
                        }
                    }
                });

                // 防止下拉菜單內部點擊關閉
                dropdownContent.addEventListener('click', (e) => {
                    e.stopPropagation();
                });
            }

            // 主題切換
            document.getElementById('themeToggle').addEventListener('click', toggleTheme);

            // 令牌保存
            document.getElementById('saveTokenBtn').addEventListener('click', saveToken);

            // 項目操作按鈕
            document.getElementById('testApiBtn').addEventListener('click', testApiConnection);
            document.getElementById('generateDirBtn').addEventListener('click', generateDirectoryTree);
            document.getElementById('generateCardBtn').addEventListener('click', generateShareCard);

            // 結果操作按鈕
            document.getElementById('copyTextBtn').addEventListener('click', copyText);
            document.getElementById('copyMarkdownBtn').addEventListener('click', copyMarkdown);
            document.getElementById('downloadImageBtn').addEventListener('click', downloadImage);
            document.getElementById('downloadCardBtn').addEventListener('click', downloadCard);

            // 腳本下載
            document.getElementById('downloadBatBtn').addEventListener('click', downloadBatScript);
            document.getElementById('downloadShBtn').addEventListener('click', downloadShScript);

            // 卡片風格選擇
            document.getElementById('cardStyleSelect').addEventListener('change', changeCardStyle);

            // 鍵盤快捷鍵
            document.getElementById('projectInput').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    generateDirectoryTree();
                }
            });

            // 幫助模態框
            setupModalHandlers();
        }

        // 主題切換
        function toggleTheme() {
            AppState.updateDarkMode(!AppState.isDarkMode);

            if (AppState.isDarkMode) {
                document.body.classList.add('dark-mode');
                document.getElementById('themeToggle').innerHTML = '<i class="fas fa-sun text-gray-300"></i>';
            } else {
                document.body.classList.remove('dark-mode');
                document.getElementById('themeToggle').innerHTML = '<i class="fas fa-moon text-gray-600"></i>';
            }
        }
        
        // 保存令牌
        function saveToken() {
            const token = document.getElementById('tokenInput').value.trim();
            if (token) {
                AppState.updateToken(token);
                Utils.showElement('tokenStatus');
                document.getElementById('generateDirBtn').disabled = false;
                document.getElementById('generateCardBtn').disabled = false;
            }
        }

        // API 服務類
        const ApiService = {
            baseUrl: 'https://api.gitcode.com/api/v5',

            // 解析項目路徑
            parseProjectPath(input) {
                if (!input || typeof input !== 'string') {
                    throw new Error('請輸入有效的項目路徑');
                }

                input = input.trim()
                    .replace(/^https?:\/\//, '')
                    .replace(/^gitcode\.com\//, '')
                    .replace(/\/$/, '');

            const parts = input.split('/');
                if (parts.length !== 2 || !parts[0] || !parts[1]) {
                    throw new Error('請輸入正確的項目路徑，格式：owner/repo');
            }

            return { owner: parts[0], repo: parts[1] };
            },

            // 創建請求頭
            createHeaders(includeAuth = true) {
                const headers = {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                };

                if (includeAuth && AppState.savedToken) {
                    headers['Authorization'] = `Bearer ${AppState.savedToken}`;
                }

                return headers;
            },

            // 處理 API 響應
            async handleResponse(response, operation = 'API請求') {
                if (!response.ok) {
                    const errorText = await response.text();
                    let errorMessage;

                    switch (response.status) {
                        case 401:
                            errorMessage = '訪問令牌無效或已過期，請重新設置';
                            break;
                        case 403:
                            errorMessage = '訪問令牌權限不足，請確保已勾選相應權限';
                            break;
                        case 404:
                            errorMessage = '項目不存在或無權訪問，請檢查項目名稱是否正確';
                            break;
                        case 429:
                            errorMessage = '請求過於頻繁，請稍後再試';
                            break;
                        case 500:
                            errorMessage = '服務器內部錯誤，請稍後再試';
                            break;
                        default:
                            errorMessage = `${operation}失敗 (${response.status}): ${errorText}`;
                    }

                    throw new Error(errorMessage);
                }

                return await response.json();
            },

            // 獲取項目信息
            async getProjectInfo(owner, repo) {
                try {
                    console.log(`正在獲取項目信息: ${owner}/${repo}`);

                    const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}`, {
                        headers: this.createHeaders()
                    });

                    return await this.handleResponse(response, '獲取項目信息');
            } catch (error) {
                    console.error('獲取項目信息時發生錯誤:', error);
                if (error.name === 'TypeError' && error.message.includes('fetch')) {
                        throw new Error('網絡連接失敗，請檢查網絡連接或稍後重試');
                }
                throw error;
            }
            },
        
            // 獲取項目目錄
            async getProjectDirectory(owner, repo, path = '', depth = 0, maxDepth = 0) {
            if (maxDepth > 0 && depth >= maxDepth) {
                return [];
            }
            
            try {
                    console.log(`正在獲取目錄內容: ${owner}/${repo}/${path}`);

                    const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/contents/${path}`, {
                        headers: this.createHeaders()
                    });

                    const items = await this.handleResponse(response, '獲取目錄內容');
                    console.log(`成功獲取目錄內容，共 ${items.length} 項`);

                    // 並行處理子目錄
                    const subDirectoryPromises = items
                        .filter(item => item.type === 'dir')
                        .map(async (item) => {
                            try {
                                item.children = await this.getProjectDirectory(owner, repo, item.path, depth + 1, maxDepth);
                        } catch (error) {
                                console.warn(`獲取子目錄 ${item.path} 失敗:`, error.message);
                            item.children = [];
                        }
                            return item;
                        });

                    const processedItems = await Promise.all(subDirectoryPromises);

                    return items.map(item => {
                        if (item.type === 'dir') {
                            const processed = processedItems.find(p => p.path === item.path);
                            return processed || { ...item, children: [] };
                        }
                        return item;
                    });
            } catch (error) {
                    console.error(`獲取目錄內容時發生錯誤:`, error);
                if (error.name === 'TypeError' && error.message.includes('fetch')) {
                        throw new Error('網絡連接失敗，請檢查網絡連接或稍後重試');
                }
                throw error;
            }
        }
        };
        
        // 業務邏輯函數
        const BusinessLogic = {
            // 生成目錄樹文本
            generateDirectoryTreeText(items, prefix = '', viewType = 'all') {
            let text = '';
            items.forEach((item, index) => {
                if (viewType === 'folders' && item.type !== 'dir') {
                    return;
                }
                
                const isLast = index === items.length - 1;
                const connector = isLast ? '└── ' : '├── ';
                const icon = item.type === 'dir' ? '📁' : '📄';
                text += `${prefix}${connector}${icon} ${item.name}\n`;
                
                if (item.type === 'dir' && item.children && item.children.length > 0) {
                    const newPrefix = prefix + (isLast ? '    ' : '│   ');
                        text += this.generateDirectoryTreeText(item.children, newPrefix, viewType);
                }
            });
            return text;
            },
        
            // 生成分享卡片
            generateShareCard(projectInfo, style) {
            const cardDiv = document.createElement('div');
            
                const giteeIcon = this.createGiteeIcon();

                switch (style) {
                    case 'mac':
                        return this.createMacCard(cardDiv, projectInfo, giteeIcon);
                    case 'gitee':
                        return this.createGiteeCard(cardDiv, projectInfo, giteeIcon);
                    case 'material':
                        return this.createMaterialCard(cardDiv, projectInfo, giteeIcon);
                    case 'modern':
                        return this.createModernCard(cardDiv, projectInfo, giteeIcon);
                    default:
                        return this.createMacCard(cardDiv, projectInfo, giteeIcon);
                }
            },

            // 創建 Gitee 圖標
            createGiteeIcon() {
            const giteeIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            giteeIcon.setAttribute('viewBox', '0 0 1024 1024');
            giteeIcon.setAttribute('width', '16');
            giteeIcon.setAttribute('height', '16');
            giteeIcon.classList.add('gitee-small-icon');
            
            const giteePath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            giteePath.setAttribute('d', 'M512 1024C229.2224 1024 0 794.7776 0 512S229.2224 0 512 0s512 229.2224 512 512-229.2224 512-512 512z m259.1488-568.8832H480.4096a25.2928 25.2928 0 0 0-25.2928 25.2928l-0.0256 63.2064c0 13.952 11.3152 25.2928 25.2672 25.2928h177.024c13.9776 0 25.2928 11.3152 25.2928 25.2672v12.6464a75.8528 75.8528 0 0 1-75.8528 75.8528H366.592a25.2928 25.2928 0 0 1-25.2672-25.2928v-240.1792a75.8528 75.8528 0 0 1 75.8272-75.8528h353.9456a25.2928 25.2928 0 0 0 25.2672-25.2928l0.0768-63.2064a25.2928 25.2928 0 0 0-25.2672-25.2928H417.152a189.6192 189.6192 0 0 0-189.6192 189.6448v353.9456c0 13.9776 11.3152 25.2928 25.2928 25.2928h372.9408a170.6496 170.6496 0 0 0 170.6496-170.6496v-145.408a25.2928 25.2928 0 0 0-25.2928-25.2672z');
            giteePath.setAttribute('fill', 'currentColor');
            giteePath.setAttribute('p-id', '9455');
            
            giteeIcon.appendChild(giteePath);
                return giteeIcon
            },
            
            // 創建 macOS 風格卡片
            createMacCard(cardDiv, projectInfo, giteeIcon) {
                    cardDiv.className = 'mac-card';
                    cardDiv.innerHTML = `
                        <div class="mac-header">
                            <div class="mac-button bg-red-500"></div>
                            <div class="mac-button bg-yellow-500"></div>
                            <div class="mac-button bg-green-500"></div>
                        </div>
                        <div class="mac-content">
                            <div class="mac-info">
                                <h3 class="mac-title"></h3>
                            <p class="mac-desc">${projectInfo.description || '暫無描述'}</p>
                                <div class="mac-stats">
                                    <span><i class="fas fa-star text-yellow-400 mr-1"></i>${projectInfo.stargazers_count || 0}</span>
                                    <span><i class="fas fa-code-branch text-green-400 mr-1"></i>${projectInfo.forks_count || 0}</span>
                                    <span><i class="fas fa-circle text-blue-400 mr-1 text-xs"></i>${projectInfo.language || '未知'}</span>
                                </div>
                            </div>
                            <div class="qr-container">
                                <div id="qrcode"></div>
                            </div>
                        </div>
                    `;

                    const macTitle = cardDiv.querySelector('.mac-title');
                    macTitle.appendChild(giteeIcon.cloneNode(true));
                    macTitle.appendChild(document.createTextNode(projectInfo.full_name));
                console.log('projectInfo', projectInfo)
                this.addQRCode(cardDiv, projectInfo.http_url_to_repo);
                return cardDiv;
            },
                
            // 創建 GitCode 風格卡片
            createGiteeCard(cardDiv, projectInfo, giteeIcon) {
                    cardDiv.className = 'gitee-card';
                    cardDiv.innerHTML = `
                        <div class="gitee-header">
                            <h3 class="gitee-title"></h3>
                            <span class="gitee-badge">Public</span>
                        </div>
                        <div class="gitee-content">
                            <div class="gitee-info">
                                <p class="gitee-desc">${projectInfo.description || '暂无描述'}</p>
                                <div class="gitee-stats">
                                    <span><i class="fas fa-star mr-1"></i>${projectInfo.stargazers_count || 0}</span>
                                    <span><i class="fas fa-code-branch mr-1"></i>${projectInfo.forks_count || 0}</span>
                                    <span><i class="fas fa-circle mr-1 text-xs"></i>${projectInfo.language || '未知'}</span>
                                </div>
                            </div>
                            <div class="qr-container">
                                <div id="qrcode"></div>
                            </div>
                        </div>
                    `;

                    const giteeTitle = cardDiv.querySelector('.gitee-title');
                    giteeTitle.appendChild(giteeIcon.cloneNode(true));
                    giteeTitle.appendChild(document.createTextNode(projectInfo.full_name));

                this.addQRCode(cardDiv, projectInfo.http_url_to_repo);
                return cardDiv;
            },

            // 創建 Material 風格卡片
            createMaterialCard(cardDiv, projectInfo, giteeIcon) {
                    cardDiv.className = 'material-card';
                    cardDiv.innerHTML = `
                        <div class="material-content">
                            <div class="material-top">
                                <div class="material-info">
                                    <h3 class="material-title"></h3>
                                    <p class="material-desc">${projectInfo.description || '暂无描述'}</p>
                                </div>
                                <div class="qr-container">
                                    <div id="qrcode"></div>
                                </div>
                            </div>
                            <div class="material-divider"></div>
                            <div class="material-stats">
                                <div class="material-stats-left">
                                    <span><i class="fas fa-star mr-2"></i>${projectInfo.stargazers_count || 0}</span>
                                    <span><i class="fas fa-code-branch mr-2"></i>${projectInfo.forks_count || 0}</span>
                                </div>
                                <span><i class="fas fa-circle mr-2 text-xs"></i>${projectInfo.language || '未知'}</span>
                            </div>
                        </div>
                    `;

                    const materialTitle = cardDiv.querySelector('.material-title');
                    materialTitle.appendChild(giteeIcon.cloneNode(true));
                    materialTitle.appendChild(document.createTextNode(projectInfo.full_name));

                this.addQRCode(cardDiv, projectInfo.http_url_to_repo);
                return cardDiv;
            },

            // 創建 Modern 風格卡片
            createModernCard(cardDiv, projectInfo, giteeIcon) {
                    cardDiv.className = 'modern-card';
                    cardDiv.innerHTML = `
                        <div class="modern-content">
                            <div>
                                <h3 class="modern-title"></h3>
                                <p class="modern-desc">${projectInfo.description || '暂无描述'}</p>
                            </div>
                            <div class="modern-footer">
                                <div class="modern-stats">
                                    <div class="modern-stat"><i class="fas fa-star mr-2"></i>${projectInfo.stargazers_count || 0} Stars</div>
                                    <div class="modern-stat"><i class="fas fa-code-branch mr-2"></i>${projectInfo.forks_count || 0} Forks</div>
                                    <div class="modern-stat"><i class="fas fa-circle mr-2 text-xs"></i>${projectInfo.language || '未知'}</div>
                                </div>
                                <div class="qr-container">
                                    <div id="qrcode"></div>
                                </div>
                            </div>
                        </div>
                    `;

                    const modernTitle = cardDiv.querySelector('.modern-title');
                    modernTitle.appendChild(giteeIcon.cloneNode(true));
                    modernTitle.appendChild(document.createTextNode(projectInfo.full_name));

                this.addQRCode(cardDiv, projectInfo.http_url_to_repo);
                return cardDiv;
            },

            // 添加二維碼
            addQRCode(cardDiv, url) {
                const qrcodeDiv = cardDiv.querySelector('#qrcode');
                if (!qrcodeDiv) {
                    console.error('找不到二維碼容器');
                    return;
                }

                // 顯示加載狀態
                qrcodeDiv.innerHTML = '<div style="color: #666; font-size: 12px; text-align: center; padding: 20px;">Loading QR Code...</div>';

                // 使用QRCode庫生成二維碼
                const generateQRWithLibrary = () => {
                    try {
                        // 清空容器
                        qrcodeDiv.innerHTML = '';
                        // url
                        // 創建二維碼
                        const qr = new QRCode(qrcodeDiv, {
                            text: url,
                        width: 96,
                        height: 96,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.H
                    });

                        console.log('二維碼生成成功:', url);
                        return true;

                    } catch (error) {
                        console.error('QRCode庫生成失敗:', error);
                        return false;
                    }
                };

                // 使用在線API生成二維碼作為備選
                const generateQRWithAPI = () => {
                    try {
                        const encodedUrl = encodeURIComponent(url);
                        const qrApiUrl = `https://api.qrserver.com/v1/create-qr-code/?size=96x96&data=${encodedUrl}`;

                        qrcodeDiv.innerHTML = `<img src="${qrApiUrl}" alt="QR Code" style="width: 96px; height: 96px; border-radius: 8px;" onerror="this.parentElement.innerHTML='<div style=&quot;color: #f56565; font-size: 12px; text-align: center; padding: 20px;&quot;>QR Code API Failed</div>'">`;

                        console.log('使用API生成二維碼成功:', url);
                        return true;
                    } catch (error) {
                        console.error('API生成二維碼失敗:', error);
                        return false;
                    }
                };

                // 使用簡單的文本二維碼作為最後備選
                const generateSimpleQR = () => {
                    try {
                        qrcodeDiv.innerHTML = `
                            <div style="
                                width: 96px; 
                                height: 96px; 
                                background: #f8f9fa; 
                                border: 2px solid #dee2e6; 
                                border-radius: 8px; 
                                display: flex; 
                                flex-direction: column; 
                                align-items: center; 
                                justify-content: center; 
                                text-align: center; 
                                font-size: 10px; 
                                color: #6c757d;
                                word-break: break-all;
                                padding: 4px;
                                box-sizing: border-box;
                            ">
                                <div style="font-weight: bold; margin-bottom: 4px;">QR Code</div>
                                <div style="font-size: 8px; line-height: 1.2;">${url.length > 20 ? url.substring(0, 20) + '...' : url}</div>
                            </div>
                        `;
                        console.log('使用簡單文本二維碼成功:', url);
                        return true;
                    } catch (error) {
                        console.error('簡單文本二維碼失敗:', error);
                        return false;
                    }
                };

                // 嘗試使用QRCode庫
                if (typeof QRCode !== 'undefined') {
                    if (!generateQRWithLibrary()) {
                        // 如果庫生成失敗，嘗試API
                        if (!generateQRWithAPI()) {
                            // 如果API也失敗，使用簡單文本
                            generateSimpleQR();
                        }
                    }
                } else {
                    // 如果庫未加載，等待後重試
                    const retryInterval = setInterval(() => {
                        if (typeof QRCode !== 'undefined') {
                            clearInterval(retryInterval);
                            if (!generateQRWithLibrary()) {
                                if (!generateQRWithAPI()) {
                                    generateSimpleQR();
                                }
                            }
                        }
                    }, 100);

                    // 最多重試2秒，然後使用備選方案
            setTimeout(() => {
                        clearInterval(retryInterval);
                        if (typeof QRCode === 'undefined') {
                            console.log('QRCode庫加載超時，使用備選方案');
                            if (!generateQRWithAPI()) {
                                generateSimpleQR();
                            }
                        }
                    }, 2000);
                }
            }
        };

        // 主要業務函數
        async function testApiConnection() {
            const input = document.getElementById('projectInput').value.trim();
            if (!input) {
                Utils.showError(I18n.t('enter_project_address'));
                return;
            }
            
            try {
                const { owner, repo } = ApiService.parseProjectPath(input);
                console.log(`測試API連接: ${owner}/${repo}`);

                const projectInfo = await ApiService.getProjectInfo(owner, repo);
                Utils.showSuccess(`${I18n.t('api_test_success')} ${projectInfo.full_name || projectInfo.name}`);
            } catch (error) {
                console.error('API測試失敗:', error);
                Utils.showError(`${I18n.t('api_test_failed')} ${error.message}`);
            }
        }
        
        async function generateDirectoryTree() {
            const input = document.getElementById('projectInput').value.trim();
            if (!input) {
                Utils.showError(I18n.t('enter_project_address'));
                return;
            }
            
            const depth = parseInt(document.getElementById('depthSelect').value);
            const viewType = document.getElementById('viewTypeSelect').value;
            
            try {
                const { owner, repo } = ApiService.parseProjectPath(input);

                Utils.hideElement('dirResultSection');
                Utils.hideElement('errorSection');
                Utils.hideElement('successSection');
                Utils.showElement('dirLoadingSection');
                
                const [projectInfo, directory] = await Promise.all([
                    ApiService.getProjectInfo(owner, repo),
                    ApiService.getProjectDirectory(owner, repo, '', 0, depth)
                ]);
                
                AppState.currentProjectInfo = projectInfo;
                AppState.currentDirectoryItems = directory;
                
                AppState.fullDirectoryTree = `${projectInfo.name}\n${BusinessLogic.generateDirectoryTreeText(directory, '', 'all')}`;
                AppState.currentDirectoryTree = `${projectInfo.name}\n${BusinessLogic.generateDirectoryTreeText(directory, '', viewType)}`;
                
                document.getElementById('directoryTreeContainer').innerHTML = `<pre>${AppState.currentDirectoryTree}</pre>`;
                
                Utils.hideElement('dirLoadingSection');
                Utils.showElement('dirResultSection');
            } catch (error) {
                Utils.showError(error.message);
            }
        }
        
        async function generateShareCard() {
            const input = document.getElementById('projectInput').value.trim();
            if (!input) {
                Utils.showError(I18n.t('enter_project_address'));
                return;
            }

            try {
                const { owner, repo } = ApiService.parseProjectPath(input);

                Utils.hideElement('cardResultSection');
                Utils.hideElement('errorSection');
                Utils.hideElement('successSection');
                Utils.showElement('cardLoadingSection');

                AppState.currentProjectInfo = await ApiService.getProjectInfo(owner, repo);
                
                const container = document.getElementById('shareCardContainer');
                container.innerHTML = '';
                const card = BusinessLogic.generateShareCard(AppState.currentProjectInfo, AppState.selectedCardStyle);
                container.appendChild(card);
                
                Utils.hideElement('cardLoadingSection');
                Utils.showElement('cardResultSection');
            } catch (error) {
                Utils.showError(error.message);
            }
        }

        // 輔助函數
        function copyText() {
            if (AppState.currentDirectoryTree) {
                navigator.clipboard.writeText(AppState.currentDirectoryTree);
                Utils.showButtonFeedback(document.getElementById('copyTextBtn'));
            }
        }

        function copyMarkdown() {
            if (AppState.currentDirectoryTree) {
                const markdown = `\`\`\`\n${AppState.currentDirectoryTree}\`\`\``;
                navigator.clipboard.writeText(markdown);
                Utils.showButtonFeedback(document.getElementById('copyMarkdownBtn'));
            }
        }
        
        async function downloadImage() {
            if (!AppState.fullDirectoryTree || !AppState.currentProjectInfo) return;
            
            const tempContainer = document.createElement('div');
            tempContainer.style.position = 'absolute';
            tempContainer.style.left = '-9999px';
            
            const macTreeContainer = document.createElement('div');
            macTreeContainer.className = 'mac-tree-container';
            
            const macHeader = document.createElement('div');
            macHeader.className = 'mac-tree-header';
            macHeader.innerHTML = `
                <div class="mac-button bg-red-500"></div>
                <div class="mac-button bg-yellow-500"></div>
                <div class="mac-button bg-green-500"></div>
                <div style="margin-left: 10px; display: flex; align-items: center;">
                    <svg t="1754809639705" class="w-5 h-5 text-red-600 mr-2" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9454">
                        <path d="M512 1024C229.2224 1024 0 794.7776 0 512S229.2224 0 512 0s512 229.2224 512 512-229.2224 512-512 512z m259.1488-568.8832H480.4096a25.2928 25.2928 0 0 0-25.2928 25.2928l-0.0256 63.2064c0 13.952 11.3152 25.2928 25.2672 25.2928h177.024c13.9776 0 25.2928 11.3152 25.2928 25.2672v12.6464a75.8528 75.8528 0 0 1-75.8528 75.8528H366.592a25.2928 25.2928 0 0 1-25.2672-25.2928v-240.1792a75.8528 75.8528 0 0 1 75.8272-75.8528h353.9456a25.2928 25.2928 0 0 0 25.2672-25.2928l0.0768-63.2064a25.2928 25.2928 0 0 0-25.2672-25.2928H417.152a189.6192 189.6192 0 0 0-189.6192 189.6448v353.9456c0 13.9776 11.3152 25.2928 25.2928 25.2928h372.9408a170.6496 170.6496 0 0 0 170.6496-170.6496v-145.408a25.2928 25.2928 0 0 0-25.2928-25.2672z" fill="currentColor" p-id="9455"></path>
                    </svg>
                    <span style="color: #f7fafc; font-weight: 600;">${AppState.currentProjectInfo.full_name}</span>
                </div>
            `;
            
            const macContent = document.createElement('div');
            macContent.className = 'mac-tree-content';
            macContent.textContent = AppState.fullDirectoryTree;
            
            macTreeContainer.appendChild(macHeader);
            macTreeContainer.appendChild(macContent);
            tempContainer.appendChild(macTreeContainer);
            document.body.appendChild(tempContainer);
            
            try {
                const contentHeight = macContent.scrollHeight;
                macTreeContainer.style.height = (contentHeight + 80) + 'px';
                
                const canvas = await html2canvas(macTreeContainer, {
                    backgroundColor: null,
                    scale: 2,
                    height: contentHeight + 80,
                    windowHeight: contentHeight + 80
                });
                
                const link = document.createElement('a');
                link.download = `${AppState.currentProjectInfo.full_name.replace('/', '-')}-directory.png`;
                link.href = canvas.toDataURL('image/png');
                link.click();
                
                Utils.showButtonFeedback(document.getElementById('downloadImageBtn'), I18n.t('downloaded'));
            } catch (error) {
                console.error('生成圖片失敗:', error);
                Utils.showError(I18n.t('generate_image_failed'));
            } finally {
                document.body.removeChild(tempContainer);
            }
        }

        async function downloadCard() {
            if (!AppState.currentProjectInfo) return;

            try {
                const cardElement = document.querySelector('#shareCardContainer > div');
                if (!cardElement) {
                    Utils.showError(I18n.t('please_generate_card_first'));
                    return;
                }

                const canvas = await html2canvas(cardElement, {
                    backgroundColor: null,
                    scale: 2
                });

                const link = document.createElement('a');
                link.download = `${AppState.currentProjectInfo.full_name.replace('/', '-')}-card.png`;
                link.href = canvas.toDataURL('image/png');
                link.click();

                Utils.showButtonFeedback(document.getElementById('downloadCardBtn'), I18n.t('downloaded'));
            } catch (error) {
                console.error('生成卡片圖片失敗:', error);
                Utils.showError(I18n.t('generate_card_failed'));
            }
        }

        function changeCardStyle(e) {
            AppState.updateCardStyle(e.target.value);
            if (AppState.currentProjectInfo) {
                const container = document.getElementById('shareCardContainer');
                container.innerHTML = '';
                const card = BusinessLogic.generateShareCard(AppState.currentProjectInfo, AppState.selectedCardStyle);
                container.appendChild(card);
            }
        }

        // 腳本下載函數
        function downloadBatScript(e) {
            e.preventDefault();
            if (!AppState.currentDirectoryItems || !AppState.currentProjectInfo) return;
            
            let scriptContent = `@echo off\necho Creating directory structure for ${AppState.currentProjectInfo.full_name}\necho.\n`;
            
            function generateBatScript(items, path = '') {
                items.forEach(item => {
                    const itemPath = path ? `${path}\\${item.name}` : item.name;
                    if (item.type === 'dir') {
                        scriptContent += `mkdir "${itemPath}"\n`;
                        if (item.children && item.children.length > 0) {
                            generateBatScript(item.children, itemPath);
                        }
                    } else {
                        scriptContent += `echo. > "${itemPath}"\n`;
                    }
                });
            }
            
            generateBatScript(AppState.currentDirectoryItems);
            scriptContent += `\necho Directory structure created successfully!\npause`;
            
            const blob = new Blob([scriptContent], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.download = `${AppState.currentProjectInfo.full_name.replace('/', '-')}-structure.bat`;
            link.href = url;
            link.click();
            URL.revokeObjectURL(url);
        }
        
        function downloadShScript(e) {
            e.preventDefault();
            if (!AppState.currentDirectoryItems || !AppState.currentProjectInfo) return;
            
            let scriptContent = `#!/bin/bash\necho "Creating directory structure for ${AppState.currentProjectInfo.full_name}"\necho\n`;
            
            function generateShScript(items, path = '') {
                items.forEach(item => {
                    const itemPath = path ? `${path}/${item.name}` : item.name;
                    if (item.type === 'dir') {
                        scriptContent += `mkdir -p "${itemPath}"\n`;
                        if (item.children && item.children.length > 0) {
                            generateShScript(item.children, itemPath);
                        }
                    } else {
                        scriptContent += `touch "${itemPath}"\n`;
                    }
                });
            }
            
            generateShScript(AppState.currentDirectoryItems);
            scriptContent += `\necho "Directory structure created successfully!"`;
            
            const blob = new Blob([scriptContent], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.download = `${AppState.currentProjectInfo.full_name.replace('/', '-')}-structure.sh`;
            link.href = url;
            link.click();
            URL.revokeObjectURL(url);
        }

        // 模態框處理
        function setupModalHandlers() {
        const modal = document.getElementById('helpModal');
        const helpBtn = document.getElementById('helpBtn');
        const closeBtn = document.querySelector('.close');
        
        helpBtn.addEventListener('click', () => {
            modal.style.display = 'block';
        });
        
        closeBtn.addEventListener('click', () => {
            modal.style.display = 'none';
        });
        
        window.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.style.display = 'none';
                }
            });
        }

        // 性能優化：添加加載狀態管理
        const LoadingManager = {
            setLoading(elementId, isLoading) {
                const element = document.getElementById(elementId);
                if (element) {
                    if (isLoading) {
                        element.classList.add('loading');
                        element.disabled = true;
                    } else {
                        element.classList.remove('loading');
                        element.disabled = false;
                    }
                }
            },

            setMultipleLoading(elementIds, isLoading) {
                elementIds.forEach(id => this.setLoading(id, isLoading));
            }
        };

        // 錯誤邊界處理
        window.addEventListener('error', (event) => {
            console.error('全局錯誤:', event.error);
            Utils.showError(I18n.t('unexpected_error'));
        });

        window.addEventListener('unhandledrejection', (event) => {
            console.error('未處理的 Promise 拒絕:', event.reason);
            Utils.showError(I18n.t('request_failed'));
        });

        // 添加 details 元素動畫處理
        document.querySelector('details').addEventListener('toggle', function () {
            const icon = this.querySelector('i.fa-chevron-down');
            if (icon) {
                if (this.open) {
                    icon.style.transform = 'rotate(180deg)';
                } else {
                    icon.style.transform = 'rotate(0deg)';
                }
            }
        });
    </script>
</body>

</html>